0 votes

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)));


Thank you for your help

in Engine by (18 points)
edited by

1 Answer

0 votes

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.

by (29,036 points)

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.


Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.