How to access a root (note2D) node from a pure c# class ?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Nennig

Hello there,

I have a node in my scene called Game (Node2D). This is the root of my scene.
Within the C# script (Game.cs) attached to this node I call a C# class named Song.
The Song class will call a Chord class and the Chord class will call a Note class…

Something like this:

mySong = new Song(this) // from Game.cs
…new Chord(game) // from Song.cs
…new Note(game). // from Chord.cs

From the Note class, I want to instantiate a sprite on my Game node.
The following works but if possible if you like to get ride of passing the game along these classes. I would like to kill the argument “Node2D game” from the constructors of the Song.cs, Chord.cs and Note.cs classes.

What can I do to the Note class to grab the Game node and do the same as below?

public Note(Node2D game)
{
    
// this works
this.game = game;
    this.isvisible = true;
    GD.Print("new note created !!");
    newNote = (Sprite)icon.Instance();
    newNote.SetPosition(new Vector2(RandomNumber(100,800),RandomNumber(100, 500)));
    game.AddChild(newNote);

}

Thank you for your help

:bust_in_silhouette: Reply From: Zylann

If Note is not a Node itself, passing the game around is actually a common solution.

Another way is to store it in a static variable so that all C# code can access it from anywhere, but it might be dangerous if you switch scenes (you want to reset it to null and make sure you don’t access it at wrong time) and it’s often considered a bad practice in the long run.

Another way is to not architecture your game this way: if Note always instances a node, why not make Note a node itself?
You could also consider using functions instead of classes.

Thanks a lot for your help and response Zylann !
For my project I think now that it is best to stick with passing the game around to classes.

bye

Nennig | 2019-07-20 15:35