- Home /
I can't get 2DCollider to work.
I have object spawning at random locations that fall down, all of them have rigidbodies attached. I've created a zone where I want anything entering it be destroyed in order to clean all the leftover clones that bypass the player. Here's my code.
enter code hereusing UnityEngine;
using System.Collections;
public class Cleaner : MonoBehaviour
{
void OnTriggerEnter2D (Collider2D other)
{
Destroy(other.gameObject);
Debug.Log ("Cought");
}
}
I've tried having both the zone and the objects set as triggers, tried both collision and trigger enter functions, tried both having rigidbodies...but to no avail. I just want the trigger zone to destroy anything that goes through it.
I've added a Debug.Log and it looks like this code doesn't even register that something is passing through it.
First step is to always Debug to see if the collider is working. Add this above the Destroy line :
Debug.Log( gameObject.name + " trigger entered by " + other.gameObject.name );
So, maybe better results redoing the question with title "Can't get 2DTrigger to work?"
Answer by origonn · Apr 05, 2014 at 05:55 PM
Your parameter is a Collider2D instead of a Collision2D.
With the OnTriggerEnter2D, is one of the colliders set to be isTrigger?
Thanks for the collider help. Yes, I've tried setting it to be trigger-trigger and trigger-collider.
For the trigger, the OnTriggerEnter2D method will be called in the object that is set to isTrigger when a collider enters it. So if you want your collidable object to dissapear when it enters a zone, have that zone's collider set to isTrigger, have the object entering it to be a regular collider, and the OnTriggerEnter2D method will be triggered in the zone script and must be present there, not in the script of the object being destroyed
Oh my god...that's exactly how I set it up, however your isTrigger tip made me check the collider in the inspector again...and it just happened so that I forgot to add that script to the object...so embarrassing.
Hmmm...in 3D, you need the same set-up: a collider, a trigger, and a proper OnTriggerEnter. But OnTriggerEnter can be on either object's script (or both and called for each.)
I don't use 2D. Are you sure OnTriggerEnter2D must be on the trigger?
I don't think it matters where the script is attached for it to work, you just have to attach it to the object that you want to have the specific behavior. Worked for me.
Your answer
Follow this Question
Related Questions
Collision With Trigger, Then Add Points To Counter, Then Destroy 1 Answer
OnMouseDrag issue, Event System 0 Answers
Triggers Interacting with Triggers 0 Answers
C# Invalid Points Assigned to 2D Edge Collider 1 Answer
Sword Kills Enemies From Far Away 3 Answers