How to instanciate an object (script?) with some variables?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By nwgdusr999

I’m trying to find out how you should instantiate an object containing variables? For instance, I tried;

MyObject.gd (script)

extends Reference
var var1
var var2

And then, in another script:

var MyObject= preload("res://scripts/MyObject.gd");
var myObjectInstance = MyObject.new();

But this results in a “Invalid call. Nonexistent function ‘new’ in base ‘Nil’.” I’m guessing that it’s because I’m trying to instantiate a script and not an object… So how should I go about creating an instance of the above object? It’s not a node that needs to be added to a scene, just an item to be used programmatically. Thanks!

:bust_in_silhouette: Reply From: Vrzasq

You can register class name with class_name keyword

extends Reference
class_name MyClass

And than inside other script instanciate it like that

var obj = MyClass.new()

You can do it also Your way but in that case You probably need to change var to const

Hah! So you need the class_name… Thanks!

nwgdusr999 | 2019-08-25 22:31

:bust_in_silhouette: Reply From: jujumumu

First of all I am pretty sure you can not instance a script but I could be wrong. If all the script is 2 variables just create a list of the variables.