Hi,
I have an issue with a script and hot reload:
In the script I use swap like this:
Any idea what I am doing wrong?
Everything works on first load.
Hi,
I have an issue with a script and hot reload:
In the script I use swap like this:
Any idea what I am doing wrong?
Everything works on first load.
Hi @iso74,
Can you try and do this to remove the listener?
old.app.mouse.off('mousedown', old.onMouseDown, old);
Also old.app
can be this.app
since they both point at the same Application instance.
Good point, unfortunately same behavior.
Is it possible to unload the script when changing the scene? Maybe this would help…
Issue has been solved by removing the event listener when script has been destroyed:
this.on('destroy', function () {
this.app.mouse.off('mousedown', this.onMouseDown);
});
Ah, that’s interesting. You will still want to keep that listener but cater for it in the swap function.
Could you post your full script and we can take a look on what it ‘should’ be?
Yes, but it’s related because event listeners have object scope.
Honestly I was descovering this after that also in other scripts that it is done this way in initialize function (also in examples). This script is also an example script from the box physics example called boxPlacement.js
Yes, swap isn’t commonly used unfortunately for a number of reason like the one you are discovering here.
This is how I would cater for it: https://playcanvas.com/project/1010869/overview/f-swap-events-issue
// Other code .....
// initialize code called once per entity
BoxPlacement.prototype.initialize = function () {
this.setEvents('on');
this.on('destroy', this.onDestroy, this);
};
BoxPlacement.prototype.onDestroy = function () {
this.setEvents('off');
};
BoxPlacement.prototype.setEvents = function (offOn) {
if (this.app.touch) {
this.app.touch[offOn]('touchstart', this.onTouchStart, this);
}
this.app.mouse[offOn]('mousedown', this.onMouseDown, this);
};
// Other code.....
BoxPlacement.prototype.swap = function(old) {
old.setEvents('off');
old.off('destroy', old.onDestroy, old);
this.setEvents('on');
this.on('destroy', this.onDestroy, this);
};
Cool, thank you very much!