Topic was automatically imported from the old Question2Answer platform.
Asked By
alibix
Let’s say I have a C# class attached to the root node of a scene called CustomSprite.
If I wanted to instance the scene that is part of a scene in C# from another class - Should I load it as a scene then cast it to the class type when instanced?
var CustomSprite = GD.Load("res://customsprite.tscn").Instance() as CustomSprite
or will just instancing the class work?
var CustomSprite = new CustomSprite()
What about if I want to have constructor parameters that distinguish behaviour in the scene object? Something like
var CustomSprite = new CustomSprite(Color color)
Which would then lead to that scene being instanced, and the scene using that parameter in some way. Like setting it’s colour to the specified colour.
PackedScene packedScene =
ResourceLoader.Load(“res://CustomSprite.tscn”) as PackedScene;
CustomSprite customSprite = packedScene.Instance() as CustomSprite;
AddChild(customSprite);
Instancing a class will just load “the C# class”. It wont load the whole scene. But it would be possible to generate the CustomSprite inside that class.
Yeah I think I get it. I’ve just made most of my classes abstract because they technically don’t get instantiated.
I know this was already answered, but I found another post with the same question (in GDScript), which gives an example of a work-around that I thought might be helpful.
As juppi said, instancing a class and a scene are two different things - one is a C# object, the other is a Godot object/thing. It’s like having a skeleton vs a body. The foundation is the same, and you can treat the scene like a C# object (i.e. call any user defined functions). But the scene does extra work that comes with being a Godot object, like creating all the sub-nodes that are part of the scene, loading resources, etc. This thread explains it better.
Anyways, the work-around can be done similarly in C#. Just define some public void Init(Color color) { ... } function for your CustomSprite class.
And then you can do,
var CustomSprite = GD.Load("res://customsprite.tscn").Instance() as CustomSprite var color = new Color(...) CustomSprite.Init(color) AddChild(CustomSprite)