I have code that programmatically creates a collision sphere on an enemy Entity and adds listeners to triggerenter
and triggerleave
using an anonymous function.
// enemyEntity
var detectionSphere = new pc.Entity();
var selfEntity = this.entity;
detectionSphere.addComponent("collision", {
type: "sphere",
radius: this.enemyDetectionRadius
});
detectionSphere.collision.on("triggerenter", function( other ) {
if ( other.tags.has("player") ) {
selfEntity.fire("onplayerdetected");
}
}, this);
detectionSphere.collision.on("triggerleave", function( other ) {
if ( other.tags.has("player") ) {
selfEntity.fire("onplayerundetected");
}
}, this);
detectionSphere.on("destroy", function() {
detectionSphere.collision.off("triggerenter");
detectionSphere.collision.off("triggerleave");
});
selfEntity.addChild(detectionSphere);
// bullet
Bullet.prototype.initialize = function() {
this.entity.collision.once('collisionstart', this.onCollisionStart, this);
};
Bullet.prototype.onCollisionStart = function(result) {
if (result.other.tags.has("player")) {
result.other.fire("onbullethit",this.bulletBaseDamage);
this.entity.destroy();
}
};
When the enemy gets destroy()
ed and a bullet hits the collisionComponent just before the enemy is completely destroyed, triggerenter is still fired which leads to an error where the Entity is undefined.
Uncaught TypeError: Cannot read property 'off' of undefined
at Entity.<anonymous> (enemyController.js?id=29849166&branchId=d7cd3d63-cfa9-4b70-a4cb-3790f97433dc:71)
at Entity.fire (playcanvas-stable.js:769)
at Entity.destroy (playcanvas-stable.js:40744)
...
What could be causing this behavior and is there a way to avoid it from happening?