Godot: Can't instantiate class from within itself

Created on 10 Sep 2017  路  7Comments  路  Source: godotengine/godot

Operating system or device, Godot version, GPU Model and driver (if graphics related):

Solus 3 64-bit (Linux), Godot 2.1.4 Stable

Issue description:

You can't instantiate a class from within itself. Here's an example:

extends Spatial

class Test:

    func _init():
        print("Hello, Test.")

    func create_new():
        print("Creating a new one...")
        var n = Test.new() # This doesn't work - it won't even compile.

func _ready():
    var t = Test.new()

archived

All 7 comments

see this one. #2012
does it work with var n = get_script().new() instead of var n = Test.new()?

Hey, thanks, it does work! But I'm not sure why get_script() returns the enclosing class and not the class defined in the file (i.e. what extends Spatial)...?

But I'm not sure why get_script() returns the enclosing class and not the class defined in the file (i.e. what extends Spatial)...?

This happens because get_script is a method of the Object class, and thus does not know anything about which file defines the script.

this should be documented in gdscript section. it's a special and gdscript specific case, comparing to other languages.

This happens because get_script is a method of the Object class, and thus does not know anything about which file defines the script.

But the "script" is referring to the script file the classes exist in, right?

this should be documented in gdscript section. it's a special and gdscript specific case, comparing to other languages.

Yeah, I agree.

get_script doesn't seem to work from a static function since "Parse Error: Can't call non-static function from a static function. I would like to make static creation funcs likeMyClass.from_string( value )`, but I can't find a way to create the object from that static function. Any ideas?

@cgbeutler Support for creating new instances in a static function is being tracked in https://github.com/godotengine/godot/issues/27491.

Was this page helpful?
0 / 5 - 0 ratings