The way I chose to structure my project is putting Player's scene outside of Map's scene, and I have a main node called "Game" that glue all together. But sometimes the Map node need some information about the player, like position, velocity, etc. and for this, I created a Singleton_called Player_ that stores the player instance and other pertinent information (like MAX_SPEED, ACCELERATION, etc.). Constant/enums variables isn't a big deal to have in global scope, right? But having a global variable to point for Player's instance breaks OOP good practices. How can I manage to have access to player object without using global variables?


A real example: all the enemies instances are inside Map's scene, these enemies need to know where the player is located all the time, and for this, they are using the Player's singleton to get information about the player.

I think using a singleton/autoload script is probably fine. Ultimately, “good code” practices are something to keep in mind, but getting it working first is important and more often than not, working code doesn’t always follow “good” code. Not to say good practices are not important! Writing code you and others can understand is great and practices can help with this, but sometimes code just has to be what it is.

That said, you can use groups if you want to avoid using a singleton/autload, and just have the player as the only member of the group. Then you can use the get_nodes_in_group function to get the player node.

Thanks for the help.

I see that Godot suggests using NodePath to inject dependencies. But I need to create a new instance of this node to use him on the scene, correct? So, this wouldn't solve my problem of needing to get a node instance already present in my scene tree.

Yeah, node paths as a way to help with dependencies only really works if the nodes are already in the scene and/or are not being instanced at runtime without their dependencies. I don't think it would help in this case, if I am understanding the situation correctly.

2 years later