+1 vote

Hi, I have a simple class written in GDScript with one method, stored in a file called SomeClass.gd

extends Node
class_name SomeClass
 
func aaa():
    print("aaa called");

Now I want to create an instance of this and save it on the drive as a PackedScene. Later, I want to load the PackedScene in an editor script (plugin), instance it and call the aaa() method. However, I'm getting errors when I do this. I've created this editor script to reproduce the issue.

tool
extends EditorScript
 
 
func _run() -> void:
    # create our node and call aaa to make sure it works
    var node = SomeClass.new();
    node.aaa(); # works
    
    # pack the node into a packedscene
    var pck = PackedScene.new();
    if(pck.pack(node) != OK):
        printerr("error");
        return;
    # (at this point in my original script i would save this to the drive and later use it like this)
    # instance our node
    var instance = pck.instance();
    
    if(
        (instance is SomeClass) &&    # double check that it's still SomeClass
        (instance.has_method("aaa"))  # and that it has the "aaa" method
    ):
        instance.call_deferred("aaa"); # gives Error calling deferred method: 'Node(SomeClass.gd)::aaa': Method not found..
        instance.aaa(); # gives Invalid call. Nonexistent function 'aaa' in base 'Node (SomeClass.gd)'.
        print("Called!");
 

When run, it produces two errors relating to a method not being found or being nonexistent. However, it seems like this should work because instance is of type SomeClass and has method aaa. Why does this fail? How can I make this work? I should also mention that this works completely if it's run ingame and not as an editor script, however I need it to work inside of the editor.

in Engine by (22 points)

1 Answer

0 votes
Best answer

The solution to my problem was to add the tool keyword to SomeClass.gd like this:

tool
extends Node
class_name SomeClass
 
func aaa():
    print("aaa called");

This tells the GDScript compiler to load the script when instancing it inside of the editor, otherwise it remains as a PlaceHolderScriptInstance and the calls fail.

by (22 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.