- Home /
Simple on Collision Help (C#)
Hi Guys, I think i have a very simple problem. Basically i want a collision script. So when my player touches the spikes he dies. i have made a script but it just wont work, i am a beginner by the way. Please it would be nice if you help.
Thank You
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);
}
}
}
Debug to check whether collision actually happens like
void OnCollisionEnter(Collision collision)
{
Debug.Log(collision.gameObject.name);
if (collision.gameObject.name == "Spikes") {
Destroy(collision.gameObject);
}
}
Answer by clunk47 · Feb 17, 2014 at 06:54 PM
Looks like you're using Rigidbody2D. For some reason w/ the 2D stuff, I can only get collisions to work correctly if both objects included have Collider2D AND Rigidbody2D. You also need to use OnCollisionEnter2D, not OnCollisionEnter.
YES!! it worked thank you. i just need to respawn the player now.
thanks for the heads up, i have not done anything with Unity on 2D framework, but good to know it before. Gusic, mark this question as the answer
Answer by poncho · Feb 17, 2014 at 05:35 PM
I am not sure from this code that if the player is the one with the PlayerDie Script, or if the spikes have the script, since the collision is expecting to be against "Spikes", i will asume that the player has the script, then collission.gameobject will be the spikes, meaning that if the player collides with the spikes the object to be destroyed would be the spikes, if you would want the player to be destroyed use Destroy(gameObject); in case the script is attached to the player
i changed it to gameObject but it still wont be destroyed(the player) i have attached the script to the player, so when the player hits the spikes he dies.
make sure both gameobjects have colliders and are not nriggers
THAN$$anonymous$$ YOU! I had is trigger on my obstacle and you finally fixed it! :D
it still doesnt work the player still doesnt get destroyed.
$$anonymous$$ake sure the thing with the script has a rigidbody attached. Also see this: http://unitygems.com/gotchas
$$anonymous$$y player does have a rigid body. look http://gyazo.com/79ada36bd80c6aadeac581aeee18a3a9
Your answer
Follow this Question
Related Questions
How to only delete one of two collided objects? 1 Answer
2D C# destroy a GameObject on collision 2 Answers
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Destroy object on touch of object with specific class 3 Answers
gameObject doesn't self-destruct after collision c# 2 Answers