How to use a variable that was assigned on the first frame, after the first frame?

Hello all,

I’ve been trying to set up a WebSocket system using JS. The problem is that the variable becomes undefined after the first frame has passed because it was not defined in that loop. Is there a way to use said variable from the second frame onwards? So I can properly send out my events?

Below is my code relating to the issue.

if (runtimeScene.getTimeManager().isFirstFrame()) {
    var socket = new WebSocket(url);
    socket.addEventListener("open", (e) => {
        response.setString(`Succefully connected.`);
        console.log("Success");

       socket.addEventListener("message", (e) => {
          response.setString(`${e.data}`);
        });
    });

    socket.addEventListener("error", (e) => {
          response.setString(`Failed to connect to server.`);
          console.log("Failed");
    });
}

if (runtimeScene.getGame().getInputManager().isKeyPressed(13)) {
    if (textBox.getString() != "") {
        sender.setString(``);

        socket.send("Test");
        // This should send the response back, except socket is undefined.
    }
}

Welcome @CoolSlimbo!

I’m not very familiar with raw JS, but in GDevelop’s UI there are three types are variables:

  • Global
  • Scene
  • Object

I’m not sure what type of variable you’re using here (if it’s one of the above types or just a generic JS variable), but perhaps it’s worth looking into using a global or scene variable in JS…

There is a websocket client extension already, no need to use JavaScript for that.

I understand there is an extension and all. But is there still a possibility to do so within JavaScript. Would I have to store the ws object into a global/scene variable to do so?