access node without knowing parents name

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By hermo

Hello! My 2d platformer game is structured like this:


  • tilemap
  • player
  • enemys

The problem is that the player’s script needs to access the tilemap and other nodes.

If I do get_node(‘/root/level03/tilemap’) it works but then the next level04 won’t work.

If I do get_parent().get_child(0) it also works but then I have to remember to keep the same structure all across the levels.

I thought in something like store a variable CURRENT_LEVEL=00 and increase it and then just get_node(level_CURRENT_LEVEL /tilemap) would be perfect but I can’t make it work
Is there any other way to do it?

Thank you!

just my idea not sure work or not but

var map_lvl = 1
var node ="level" + map_lvl


potatobanana | 2020-02-13 06:34

:bust_in_silhouette: Reply From: Jason Swearingen

get_tree().root.find_node() i think.

:bust_in_silhouette: Reply From: Sween123

Definitely you can use variables. Like CURRENTLEVEL you used.
There are many ways to do this, it’s about how you construct the program.
An example way to control different levels: Before you start the game, assign which level will lead to which level by using a variable. For example, in level_1, you use lead_to_level = LEVEL_2 where LEVEL_2 is a level scene.
You can also keep all the level scenes into an array if you want.
There are many different ways.