- Home /
OnTriggerEnter2D does not work on inactive objects?
On key press, Object A makes Object B active and on key up, makes it inactive. Everytime Object B is active, I need to check for collisions on Object B for which I have the following code. I'm not getting any collisions being detected. What am I doing wrong ?
using UnityEngine;
using System.Collections;
public class DestroyRadius : MonoBehaviour {
private void OnTriggerEnter2D(Collider2D kaboom)
{
if (kaboom.gameObject.tag == "Crowd")
{
Debug.Log("Object B is colliding with crowd");
GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerHealth>().DamagePlayer(26);
}
}
Answer by Tomer-Barkan · Apr 14, 2014 at 08:47 AM
When a GameObject is in active, it is as if it doesn't exist. Other than directly calling methods of scripts attached to this object, or changing it's properties directly from another script, there is not much you can do with it.
Some of the things that won't work on an inactive GameObject: No physics calculations (including movement, collisions, forces, etc), it will not be rendered, no lifecycle calls (update, ongui, fixedupdate).
So yes, in order for the object to get collision calls it needs to be active. Consider disabling only the renderer, then the object will appear but will not be visible to the camera:
renderer.enabled = false;
I changed my other code so that Object B is never inactive anymore. On key down, the renderer and collider2d become enabled and on key up, they become disabled. So this behavior is basically similar to having it become active and inactive as before.
But, the code for Object B is still not checking for collisions. The code is the same as above. Why would something like this happen ?
I had Is$$anonymous$$inematic checked on and Unity does not detect collisions when Is$$anonymous$$inematic is turned on. It all works now. Thanks for your suggestions ! :)