Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | Muffin |
When making an instance of a packed scene is there any way to do this with type safety in mind, instead of having to cast? Or am I missing something here?
When making a new instance of a packed scene all that you have to do is call .Instance(), which will return a Node object. Now I can cast that Node object to whatever object I “know” I’m trying to make (lets say it’s a projectile), so I will write something like:
// Declaring variable
private Projectile m_projectile;
// Constructor
public Foo (PackedScene packedSceneOfProjectile)
…
blah blah you get the picture
// Called in some method
Projectile projectile = (Projectile)m_packedSceneOfProjectile.Instance();
This doesn’t seem right, am I missing something here? Couldn’t this lead to all kinds of runtime errors?
If you know that’s going to be the result of Instance()
, then I don’t see any reason not to. It does look kind of ugly when someone’s reading the source though…
Kyle Guarco | 2019-05-10 00:18
Hey Kyle thanks for the reply.
I seen this code this morning and it might be what I’m after:
extends Node class MyObject: extends Object
var dict = {}
func _ready():
var obj1 = MyObject.new()
// can now access obj1.dict
It looks as though if I extend/inherit (I’m not actually using GDScript, I’m using C#) Object then I can call the. new() method to instantiate that object, this might be what I’m after, I’ll give it a go and report back after work.
Muffin | 2019-05-10 08:51