Notify when a UnityComponent gets disabled/enabled?

Im not talking about a script you write your self. Im talking about something like an Image, or a Collider.
Is there anyway to do something like subcribe to the event of when those get called on the components?

For example, right now I would do this with a collider by creating a script that manages disabling and enabling a collider.

ColliderManager : Monobehavior {

Collider c;
public event Action<Collider> OnColliderDisable = delegate { };
public event Action<Collider> OnColliderEnable = delegate { };

OnValidate(){
c = GetComponent<Collider>();
}

public void DisableComponent(){
c.enabled = false;
OnColliderDisable(c);
}
public void EnableComponent(){
c.enabled = true;
OnColliderEnable(c);

}
}

Now I can subscribe to when the collider gets disabled for certain weird situations where I disable a collider and the OnTriggerExit does not get called, but I must maintain that I only ever disable or enable colliders through this script.

Anyone know of a different way to accomplish this?

Unity has “magic” methods OnEnable and OnDisable that will be called on your MonoBehaviour when it is enabled to disabled.

Using those, you could write a subclass of the existing collider behaviour that can detect whenever it gets enabled or disabled (for any reason) and fires off events like you’ve got in your OP. Still a script, but you don’t need the rest of the world to call your custom enable/disable methods.

You could also have a separate script that checks the status of the collider through polling (i.e. check every frame in Update whether the collider is currently enabled or not).

But…is the Unity engine doing something to enable and disable your collider, or does that only happen when your own script says to do it? If it’s only happening in your own script, then maybe the event you should really be detecting is the logic process that causes your script to enable or disable the collider, rather than the actual enabling/disabling.

1 Like