JavaScript: Access objects / variables / functions from "other" scripts

I have the following issue:
I have one Javascript Code in my main Eventsheet and a second Javasscript code in my external events.

Main Events:

var Space = 32;

if(runtimeScene.getGame().getInputManager().isKeyPressed(Space)) {
    
    MyClass.test();
    
}

External Events:

var MyClass = (function() {

    return {
        test: function() {
            console.log("Hello World");
        }
    }

})();

How can I access each other’s objects / variables / functions?

The call of MyClass.test() leads to an error cause “MyClass” is undefined. I’ve included the external events into the main events, but this doesn’t work. The scope seems to be separated. What is the way to go?

Invoke the method in a global scope like window

window.__myScopeForGD = MyClass();

After, from everywhere you can use __myScopeForGD.

1 Like

Thank you very much! This solution works perfect for me.

1 Like

To elaborate, that is because each event is its own function. var defines a variable as function scoped, so as soon as the Javascript event it is in finishes executing, it goes out of scope and is deleted. The labels at the top and bottom of the Javascript event are supposed to hint at that. By attaching the variable to the global window, it isn’t a scoped variable anymore and I’ll be accessible at anytime from anywhere.

Note that window is not a guaranteed global scope. In the future, the game might run in an environment where window is not the global scope, sou you should always attach your stuff to the gdjs global object instead, as that one is always guaranteed to be defined in a GDevelop game.

1 Like

Thanks for that hint.
would you show an example of how you would do it?