Death on collison

Hi guys,

I am pretty new to c# programming and have been playing around with colliders. I have created this script that can destroy my character when they touch the collider. The script is working in a way, when I touch the desired collider it deletes that object and allows me to pass through it, it does not allow me to destroy the object when it touches it.

 using UnityEngine;
using System.Collections;
public class PlayerDie : MonoBehaviour {
     // Use this for initialization
     void Start () {
    
     }
    
     // Update is called once per frame
     void Update () {
    
    
     }
     void OnCollisionEnter(Collision collision){
         if (collision.gameObject.name == "Spikes") {
             Destroy(collision.gameObject);       
         }
     }
}

bump

     void OnCollisionEnter(Collision collision){
         if (collision.gameObject.name == "Spikes") {
             Destroy(gameObject);      
         }
     }

I’ve tried that but it dosn’t do anything? Anything that I could be doing wrong?

if that code works but doesn’t do anything, make sure you have istrigger checked in the inspector for the object :slight_smile:

if it’s a 2d object
it needs to be OnCollisionEnter2D

what object is the script on? the player or the spikes?

Hey guys I solved this which a bit of research on the API. I enabled is triggered into my collider’s that I wanted to die from, then I inserted this code.

using UnityEngine;
using System.Collections;

public class DamagedByCollision : MonoBehaviour
{


    int health = 1;

    void OnTriggerEnter2D(Collider2D other){
        Debug.Log("Trigger!");

        health--;

        if (health <= 0)
        {
            Die();
        }
    }
    void Die()
    {
        Destroy(gameObject);
    }
}

This is for anyone else who would like help or had the same problem. I think it is because you cant you the OnCollisionEnter2D function to this kind of thing that I was using it for. Thanks guys!

Good job. You can use oncollisionenter2d to do it as well but you can work that out another time. The original code you posted wasn’t using the 2d function

1 Like