Appropriate way to "cache" get_node?

Godot Version

4.2.1

Question

Right now, I got this code here that shoots bullet at a velocity at angle. It works fine, but in this simple case, I called get_node twice. In the future, if I am to have a tank that has more weapons (imagine lots of cannons, missile launchers, etc.), I can set up my 3DMarkers on all these accordingly, but calling get_node is a bit costly as it has to traverse through the tree. I also will have multiple instances of this tank in the game.

Because of this, for the use case above, is it possible to store the coordinates of all the weapons’ 3DMarkers just once and refer to them when instantiating bullets and rockets instead of calling get_node multiple times? If so, what would be the right way? Is this more appropriate performance-wise?

Get node is the same as $path/to/my/child/node it should be pretty quick. But you can definitely cache if they will already and always exist.

@onready var my_node = get_node(mynode)

Func somefunc():
  ...
  my_node.dosomething()
  ...

#or 

var my_node = null 

Func somefunc():
  ...
  If my_node:
     my_node.dosomething()
  ...

Func equip(node):
  my_node = node

1 Like

@pennyloafers So just put all the 3DMarker nodes of all weapons into @onready variables just like that? All of these 3DMarker nodes are pretty much parts of the vehicle scene.

These are like static variables, right?

Im asking you? If the scene is static, in the sense that the weapon always exists. I.e. it’s not equipped or removeable. Then yes @onready var node = get_node(NodePath) # or $nodepath is good to use in this way.

Otherwise, if it doesn’t always exist, you need to check if the node reference is valid before you use it.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.