The issue here is a typing issue. var
infers the type from the right side of the assignment.
this is the same as writing the following:
public partial class Node2dParent : Node2D
{
//...
Node2D Child = this.GetNode<Node2D>("ParentNode2D");
GD.Print(Child.ChildVar);
}
But the Node2D class does not have a member variable “ChildVar”.
Only the Node2dchild class has this member variable.
You’re telling the compiler that it is working with a Node2D class, but what you actually want is telling it that’s a Node2dChild class.
In our case, this means changing the type you expect, from GetNode<Node2D> to GetNode<Node2dchild>:
Node2dchild Child = this.GetNode<Node2dchild>("ParentNode2D")
the same applies to the other assignment, here you want:
Node2dParent parent = this.GetNode<Node2dParent>("ParentNode2D");
In general I’d advise you to forget that var
exists in C#, at least for now - being explicit will help you build an understanding for types.
As a side node, I’m not sure if your paths / references in GetNode
are correct.
If your tree looks like this
ParentNode2D (with script Node2dParent)
→ ChildNode2D (with script Node2dchild)
then you can get the child from the parent via GetNode<Node2dchild>("ChildNode2D")
and the parent from the child via
GetParent<Node2dParent>()