Is there an event fired for when an entity is enabled/disabled

I would like a script to be able to listen out for when its own entity has been either enabled or disabled.

This API page only lists a destroy event for entity:

However this forum post seems to suggest there is in fact such an event: "enable" event doesn't trigger after initialization

I’ve tried:

this.entity.on('enable', ...)

and

this.entity.on('enabled', ...)

…but to no avail. Am I missing something? (sorry if it’s obvious)

The event doesn’t trigger when an entity is created or when the scene loads but only when you disable it and enable it again

Yeah, I read that in the above post, but I can’t seem to get it triggering even when it’s enabled later on having already been disabled. The event is just called ‘enable’ right? and I attach it to the entity?

1 Like

There is an event that is fired (surprised it isn’t in the documentation). However, if an entity starts off disabled, the initialize function of the scripts attached are not called. It gets called on the first time the pc.script gets enabled.

So the way around this is to call the callback in the initialize function and also subscribe to the event.

App.prototype.initialize = function() {        
    this.onEnable();
    this.entity.on('enable', this.onEnable, this);
};

App.prototype.onEnable = function() {        

};

Edit: I actually can’t see in the code base where the entity fires the event but the script component does fire a ‘state’ event.

App.prototype.initialize = function() {        
    this.onEnable();
    this.on('state', this.onStateChanged, this);
};

App.prototype.onStateChanged = function(state) {        

};
1 Like

Thanks yaustar. Couldn’t get the enable event to work, but the state change event seems to work fine, so I’ll go with that for now. Thank you.

In this case, if an entity is starts enabled, wouldn’t that result in the onEnable() method being called twice?
After all, there may be subscriptions to events, etc. And that’s not good.

The initialize function of script is called after the enable event on the Entity so it will not be called twice. And until the initialize function of the script is called, there is no subscription to events.

1 Like

What are the possible state values?

Check here:

https://developer.playcanvas.com/en/user-manual/scripting/anatomy/#state,-enable,-disable

1 Like