+1 vote

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.

in Engine by (35 points)

2 Answers

0 votes
Best answer
  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.
by (710 points)
selected by

Yeah I think I get it. I've just made most of my classes abstract because they technically don't get instantiated.

0 votes

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

by (14 points)
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 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 webmaster@godotengine.org with your username.