Hello, is there a way to get the value of a variable from a different node and change it? I have a variable for the current play setting in the parent node that I want to access and change from the child node. Both are Node2D's. I am using C#.

Thanks for any help!

Sabb changed the title to Get and change a variable from another node? .

Here's one way:
get_parent().some_variable = a_value

  • Sabb replied to this.

    DaveTheCoder
    Thanks!
    I forgot to mention I'm using C#.
    So I tried GetParent().variable;

    Unfortunately I get "'Node' does not contain a definition for 'play' and no accessible extension method 'play' accepting a first argument of type 'Node' could be found (are you missing a using directive or an assembly reference?)"

    I'm sure it's something simple but I'm stumped.

    I haven't used C# with Godot, so can't give accurate advice. I flagged your initial post and requested that the CSharp tag be added, so that people who use C# will see it.

    • Sabb replied to this.
      Megalomaniak changed the title to Get and change a variable from another node in C#? .

      To solve this I also auto loaded one of the nodes to try to use nodename.variable (in my case Global.speed = 100😉 but I get this error:
      An object reference is required for the non-static field, method, or property 'Global.speed'

      Anyone know what I'm doing wrong?

      Sabb Another update with half solution;
      I can't seem to get autoload to work correctly but in case anyone else stumbles on this post looking for a solution I've started simply using the direct location each time I call a variable from a different node.
      This is the line I use:
      GetNode<Global>("/root/Game/Global").play

      Obviously Global is the name of the node I created. This is working for me while though it's not terrible convenient to type all the time.

      16 days later

      Hey, I had this problem for a long time until I finally found the solution. To get the variable from another node do:

      ClassName newVariableName = GetNode<ClassName>("nodePath");

      Now you can access those variables from the node using . notation
      (eg newVariableName.variableYouDesired)

      The key thing here is that instead of putting the node type in the <>, you put the class name of the script you attached to that node that contains the variable you desire.
      This way you don't need to fuss with autoload or anything like that.

      Instead of having to type out everything each time,
      Have the newVariableName as a property and assign the get node to it in the ready function so you can just type the newVariableName instead of GetNode every time in the rest of that script.

      eg

      public ClassName newVariableName;
      
      public override void _Ready()
      {
             newVariableName = GetNode<ClassName>("nodePath");
      }