Topic was automatically imported from the old Question2Answer platform.
Asked By
karmo77
Hello I would like to know what to do if I have a “player” scene, and another scene like “weapon”, for example, and to be able to access from my “player” script, to my “weapon” script and other meaning too
The easy way:
If the other scene is an instance in the same scene then you can just do get_node(). If not you will have to instance it, you cannot make changes to an object that doesn’t exist.
The hard way:
If you for some reason don’t want the other scene to be loaded nor instanced then you can use a singleton and have a dictionary with the properties of the other scene on there which you can use again when you instance it.
I’m not sure if this is the best way (probably not), but when I need some access like that I use a singleton on autoload to store the references and access it instead
so my player.gd sends his “somevariable” to a playerdata.gd singleton on autoload so that any other node/class can access…(weapon, enemy etc)
This will create a brain mess on large projects tho… but I dont know any better way yet, curious to see better answers.
playerdata.gd (autoload)
var something = x
on any other node use
playerdata.something etc
or reference it in playernode (player.gd)
playerdata.somevar = $somelocalnode
If Weapon is a child of Player, from the script of Player you can just say $Weapon.variable or $Weapon.value. If you are going to access the Weapon several times in your script, then you can do onready var weapon = $Weapon at the top of your script and then you can just say weapon.value instead of $Weapon every time.
This is called going “down” the tree as you are a parent node accessing the variables/values of your children nodes. If you want to go “up” the tree or “horizontally” you should use signals. And there are plenty of tuts on Youtube that go into that.