- Home /
OnTriggerEnter not working
I have many objects in a 2D game that spawn on screen which are continuously travelling on the X at a certain rate. When they leave the visible area, I want them to destroy themselves, so I took someones advice and made an empty game object with a long box collider attached to it, IsTrigger is checked. However, objects pass right through this thing and they don't destroy with the following code, nor does it give me a debug message:
using UnityEngine;
using System.Collections;
public class DeleteObjects : MonoBehaviour {
void OnTriggerEnter(Collider other) {
Destroy(other.gameObject);
Debug.Log ("Object Destroyed");
}
}
All objects are on the same Z axis, so I feel like they should at least trigger the debug message. Thoughts?
Can you give more information?
Are you using 2D or 3D physics?
Is this script sitting on the trigger or on the objects?
All of the objects which I want destroyed have a Rigidbody 2D component. The game object that I'm using as the trigger does not.
I am using only 2D Physics. The trigger(with script) is sitting on an empty game object. It is not on the game objects which I want destroyed.
Answer by HarshadK · Sep 04, 2014 at 07:38 AM
For OnTrigger function to work one of the game objects must have a rigidbody attached to it. In this case your objects that you are destroying should have a rigidbody.
If you want to destroy game objects when they are no longer visible you can use MonoBehaviour.OnBecameInvisible()
Update:
Based on your recent comment, you should use OnTriggerEnter2D if you are using 2D physics.
Harshad$$anonymous$$,
Can I place OnBecameInvisible on an empty game object and it will apply to all objects? Or do I need to place this on each script on each game object?
You need to place it on every object which you want destroyed so that it will be called when that particular object is not visible.
Also check the update in my answer.