- Home /
Destroy Object On Collision?
I'm making a 2D game and need to make a block that when the player runs into it, he gets destroyed. This is my script but it isn't working. Any help?`using UnityEngine; using System.Collections;
public class Bounds : MonoBehaviour {
void OnCollisionEnter (Collision col)
{
if(col.gameObject.name == "DeathCube")
{
Destroy(col.gameObject);
}
}
} `
How are you moving your character? Does your character have a non-kinematic Rigidbody?
Answer by JayOhhh · May 30, 2014 at 04:10 PM
void OnCollisionEnter2D (Collision2D col)
{
if(col.gameObject.name == "DeathCube")
{
Destroy(col.gameObject);
}
}
First switch the method to be in 2D. Ensure that you have a 2D collider and 2D rigid body attached to both objects. Also is your DeathCube instantiated from a prefab? If it is you will need to check the actual name on your scene. Most of the times I find instatiated prefabs append the (Clone) value to the end of the name. Maybe try and putting in a debug statement to ensure you are matching the names correctly.
void OnCollisionEnter2D (Collision2D col)
{
//Check collision name
Debug.Log("collision name = " + col.gameObject.name);
if(col.gameObject.name == "DeathCube")
{
Destroy(col.gameObject);
}
}
Thank you! I had the same issue and changing Box Collider to Box Collider 2D fixed it!
Answer by Sisso · May 21, 2014 at 11:18 PM
If you are using 2D physic you must use 2D callbacks
http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.OnCollisionEnter2D.html
Like you did, Destroy.
http://docs.unity3d.com/Documentation/ScriptReference/Object.Destroy.html
Answer by dhbzaa · Apr 17, 2019 at 03:32 AM
I am using the unity 3d I want that when my jetfighter collided with mountains or terrain the jet destroyed but my script cant work void OnCollisionEnter (Collisiion col) { if(col.gameObject.name == "Player") { Destroy(col.gameObject); } }
and I put this script in terrain and mountain but it cant work