- Home /
Collision reaction not working
I have tried to get a GameObject to destroy an item when touching, yet it just does not seem to work. I have on trigger disabled on all scripts.
code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerCollider : MonoBehaviour
{
public void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log("collision");
if (collision.gameObject.CompareTag("enemy"))
{
Debug.Log("dead");
Destroy(collision.gameObject);
}
}
Which unity version are you using? Your script should work fine and I'm seeing a few questions about the same thing.
Answer by Reid_Taylor · Feb 08, 2020 at 01:49 AM
Have you tried using OnTriggerEnter()? It can give better results; only problem is it needs one of the objects to have a character controller or rigidbody which can create performance problems.
OnTriggerEnter
and OnCollisionEnter
should technically be as reliable as each other as they both use the physics engine to tell when two colliders have just touched/intersected. Also the physics framerate (`FixedUpdate`) is typically faster than the game's fps (`Update`).
Answer by Daniil-Manokhin · Feb 09, 2020 at 10:09 PM
One of the two objects need to have a RigidBody. The Rigidbody component must be added first, followed by the Collider component in the inspector window.