Godot: Cannot access Nodes when using a static method in C#

Created on 8 Sep 2020  路  6Comments  路  Source: godotengine/godot

Godot version:
v3.2.2 Mono

OS/device including version:
Windows 10 1909

Issue description:
When using a static method, one cannot get access to the Node tree.

Steps to reproduce:

  1. Make a new Project
  2. Make a C# script
  3. Make a static method and call it somehwere so it can get executed
  4. Try to call GetNode (in the static method)
archived mono

Most helpful comment

Found a workaround:

var mainLoop = Godot.Engine.GetMainLoop();
var sceneTree = mainLoop as SceneTree;
// work with the scenetree

Maybe the SceneTree::get_singleton() method should be also implemented in both Script Environments? Or something like GD.GetTree() (for c#)?

All 6 comments

I believe this is done by design. Static functions cannot access member variables or self. The same restriction also applies to GDScript.

Ok, but does it give any other method or function to access the Node Tree from inside a static function?

Hmm, in the C++ core, you can call SceneTree:: get_singleton()->do_what_you_want, but this method does not exist in GDScript and C#/Mono.

Found a workaround:

var mainLoop = Godot.Engine.GetMainLoop();
var sceneTree = mainLoop as SceneTree;
// work with the scenetree

Maybe the SceneTree::get_singleton() method should be also implemented in both Script Environments? Or something like GD.GetTree() (for c#)?

why is this issue closed without further commentary?

Sorry, I thought a conclusion was already reached.

GetNode can only be accesses from a Node instance. The normal way of accessing a node instance from a static method is by getting the scene tree root node via (SceneTree)Engine.GetMainLoop().

Maybe the SceneTree::get_singleton() method should be also implemented in both Script Environments? Or something like GD.GetTree() (for c#)?

I don't see much benefit compared to the current way tbh. In both cases for correctness you have to deal with the possibility of the main loop not being SceneTree, although it's safe to assume it always is since custom main loops are rarely used.

Was this page helpful?
0 / 5 - 0 ratings