Any way to pass node property to function?

Godot Version

4.3

Question

Any way to pass node property to function?

func _process():
  somefunc(self.position):


func somefunc(property):
  # the line below should change the node's position
  property = Vector2(newX, newY)

You can do that only with types that can be passed by reference. Vector3 is not one of these types. But you can pass an entire Object, or Node, or Node3D by reference. In your example that would be:

func _process():
  somefunc(self)

func somefunc(node: Node3D):
  node.position = Vector2(newX, newY)

Will that be ok for you, or do you have any more specific example where this would not work?

Edit:
You actually could use the Object.set() function to pass a property name. This would then look something like that:

func _process():
  somefunc(self, "position")

func somefunc(object: Object, property: StringName):
  object.set(property, Vector2(newX, newY)) 

But I don’t really like passing arguments as String, because it’s not type-safe, so I wouldn’t do that myself.

1 Like

Your second example is closest to what I want and I might go with that despite the risk. In unity this used to be a bit simpler if I recall correctly and I relied on it quite a bit. Thank you!

1 Like

True, in C# you can use the ref keyword to do that more easily.

I think it should work the same in Godot’s C#, but I never tried. You can try it out. Remember that you can mix GDScript and C# scripts within the same project, so if it makes sense to use C# for this one usecase - just go for it :slight_smile:

Would doing that work for web/html5 export? Or should I just exclusively stick to gdscript for that?

Ah, in case we’re talking web export, then unfortunately C# is still out of scope, you need to stick to GDScript.

Gotch. Thank you for your help.