How do I properly instantiate C# classes?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: 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.

:bust_in_silhouette: Reply From: juppi
  1. You can instance a whole Scene:

PackedScene packedScene =
ResourceLoader.Load(“res://CustomSprite.tscn”) as PackedScene;
CustomSprite customSprite = packedScene.Instance() as CustomSprite;

  1. 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.

alibix | 2020-05-27 13:00

:bust_in_silhouette: Reply From: aim4

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(...)