I have a scene for a 2D project with several layers that are turned on/off at various stages in the game. Each layer has a few interactive components utilizing BoxCollider2d along with OnMouseDown events. Everything works as intended when the layer is never disabled, however, if the layer is disabled and then later re-enabled via a SetActive call my OnMouseDown events never trigger.
After some digging, I found that while in play mode if I disable and then enable my BoxCollider2D for the interactive components (after the layer has been enabled) everything works fine (note: the BoxCollider2D component is enabled when I inspect). Tired of always having random unexplained issues with Unity, I put together this work around and everything is working as expected.
private void OnEnable()
{
GetComponent<Collider2D>().enabled = false;
GetComponent<Collider2D>().enabled = true;
}
In this code, I couldn’t just set the collider to true. I had to first disable then reenable the collider. Not sure if it matters but the interactive components are inherited from a base class that derives MonoBehaviour.
I mean, it’s all working now, but I really don’t want to leave bad hacks if I can avoid. This seems like something way too common to be a Unity bug, right? Is there a better solution?