Accessing script attached to nodes (C#)

Version: Godot 4.1.1

I’m trying to call a function in a script attached to a node, but none of the methods I searched ever worked, like casting the instance to the script:

SomeClass inst = GetNode<Sprite2D>("NodeName") as SomeClass;
inst.Test();

where SomeClass extends from Sprite2D and inst turned out to be null, showing that it’s an invalid cast.

Simply doing

Sprite2D inst = GetNode<Sprite2D>("NodeName");
(SomeClass)inst.Test();

doesn’t work either, with a NullReferenceException.

I’m sure that the node is not null and it has been attached with the script SomeClass.

Thank you for your help. umu

You can simply do

YourClass instance = GetNode<YourClass>("YourNodeName");

While the answer by @tibaverus is the ‘nicest’ way, your approaches should also work with the exception of missing parentheses in the second example:

((SomeClass)inst).Test();

In fact, GetNode<T> does nothing else than (T)GetNode(...).

So your problem is probably somewhere else. Are you sure that your inst is not null? You getting a NullReferenceException in the second example suggests otherwise.
Do you get a ‘Node not found’ error?

Sorry, I actually wrote

((SomeClass)inst).Test();

in my code but I got a mistake here.

I didn’t get errors like “Node not found” and I tried

inst = GetNode<Sprite2D>("NodeName");
GD.Print(inst.Position);
GD.Print(inst as SomeClass);

The position of inst was printed. I think it proves that the node is not null.
However, in the second line I got a null, indicating that it’s an invalid cast.

ok I have figured it out.

The script SomeClass has a parent class ParentClass, and ParentClass extends from Sprite2D directly while SomeClass extends from ParentClass

In this case, attaching SomeClass to the node makes the script doesn’t work.

That’s pretty weird…

Yes, this is true. But you said you are getting a NullReferenceException with this:

((SomeClass)inst).Test();

But this is only the case when inst is null, else it should be an InvalidCastException.

This should work. Does it work when you attach ParentClass to the node? Can you share the code of ParentClass and SomeClass?

OK I figured it out (again)

Firstly,

((SomeClass)inst).Test();

does throw an InvalidCastException. I got a mistake again, sorry.

Now I have found out the real reason behind the exceptions.
In ParentClass, I wrote a constructor with some parametres, which makes the editor unable to instantiate the any script extends from ParentClass and throw an MissingMemberException (I thought it was some kind of error that wasn’t related to my situation so I ignored it).
The reason why I suceeded last week when attaching ParentClass directly to the node is unclear, maybe I got things right accidentally. But now I have deleted the constructor in the ParentClass and everything works well including attaching SomeClass to the node.
Thank you for your replies!

1 Like