godotjs / GodotJS

GodotJS - Add TypeScript/JavaScript Support for Godot 4.x with v8/QuickJS
MIT License
194 stars 5 forks source link

Autoload support #18

Open GeTechG opened 15 hours ago

GeTechG commented 15 hours ago

The error appears when you open a project with autoload already added.

[JSDebugger][Debug] devtools://devtools/bundled/inspector.html?v8only=true&ws=127.0.0.1:9230/1
ERROR: FATAL: Condition "!(loaded_)" is true.
   at: is_valid (modules/GodotJS/weaver/jsb_script.h:101)

================================================================
handle_crash: Program crashed with signal 4
Engine version: Godot Engine v4.3.stable.custom_build (77dcf97d82cbfe4e4615475fa52ca03da645dbd8)
Dumping the backtrace. Please include this when reporting the bug to the project developer.

The error occurs when opening a project with already added autoloader. P.s I will add to autoload via plugin

func _enter_tree() -> void:
    add_autoload_singleton("global", "res://addons/golevate/global.ts")
    pass
ialex32x commented 6 hours ago

This situation hasn't been considered yet. I'll handle it right away.

ialex32x commented 2 hours ago

After some investigations, the assertion failure in is_valid() should have been fixed in a recent commit. Please try the latest commit on the main branch.

By the way, Global is unnecessary for TS/JS because JS supports a classical singleton pattern.

export class MyGlobals {
    private static _inst: MyGlobals;
    static get instance() { 
        if (!MyGlobals._inst) MyGlobals._inst = new MyGlobals();
        return MyGlobals._inst;
    }

    health = 0;
}

Or, just simpily:

export class AnotherGlobal {
    static readonly instance = new AnotherGlobal();
    value = 0;
}

If you still want an autoload global Node like in gdscript originally. You could write it in this way:

// `default` is needed in this way to comply the rule how GodotJSScript find it
export default class MyGlobals extends Node {
    private static _inst: MyGlobals;
    static get instance() { 
        return MyGlobals._inst;
    }

    health = 0;

    _ready() {
        MyGlobals._inst = this;
    }
}

And access it in the way like MyGlobals.instance.health = 1. It's very similar to C# as the docs mentioned here.