[SOLVED] Scene switching bug

We have switching between scenes. The first time we switch from scene 1 to scene 2, everything is fine. But when we switch back, there is an error.

https://playcanvas.com/project/951145/overview/scene-switching

I don’t see the issue when running this from the launch tab

I forgot to point out that the bug only when calling the event from outside. We have a script “WindowEventResolver” which listens to global listeners and redirects the ones we need to the application. This is done so that the application can be inserted into the page through an iframe and call events in it.

Can you list the steps to reproduce the issue please?

As you can see on video - I just call CustomEvent on window. This event catches the “WindowEventResolver” script and calls the internal “scene:switch” event, which you also called from the console, and then the process must be the same.
Here are the events that I call:

{
    var event = new CustomEvent("scene:switch",{
        detail: {
            scene: "test"
        }
    });

    window.dispatchEvent(event);
}

{
    var event = new CustomEvent("scene:switch",{
        detail: {
            scene: "test2"
        }
    });

    window.dispatchEvent(event);
}

The issue is that when the script WindowEventResolver is destroyed, it doesn’t remove the event listener for the event. So as you are changing between scenes, it continuously adds a new event listener each time with the old ones referencing deleted data.

Fixed version: PlayCanvas 3D HTML5 Game Engine

var WindowEventResolver = pc.createScript('windowEventResolver');

// initialize code called once per entity
WindowEventResolver.prototype.initialize = function() {
    // Save context
    var self = this;

    var callback = function(e) {
        self.app.fire('switch:scene', e.detail.scene);
    };

    window.addEventListener("scene:switch", callback);

    this.on('destroy', function() {
        window.removeEventListener("scene:switch", callback);
    });
};
1 Like

You’re right! That was my bad. Many thanks to you!