- Home /
[C#]Collision whit lava kills player (Unity2D)
I am making a 2d game. and in this 2d game im trying to make it so that when the player tuches the lava he dies and im not getting it to work.
using UnityEngine;
using System.Collections;
public class Collision : MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Lava")
gameObject.destroy;
}
}
this is what im trying to fix.
Answer by HarshadK · Oct 08, 2014 at 05:41 AM
It is
Destroy(gameObject);
and not gameObject.destroy.
So your code will become:
using UnityEngine;
using System.Collections;
public class Collision : MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Lava")
Destroy(gameObject);
}
}
This script should be attached to your player game object.
And make sure there is a rigidbody attached to your player and also there is a collider attached to your lava.
Also check if the tag of the lava is "Lava" and not 'lava' or something else.
Just check if the collision is occurring by using Debug.Log like this:
void OnCollisionEnter2D(Collision2D coll) {
Debug.Log(coll.gameObject.tag);
if (coll.gameObject.tag == "Lava")
Destroy(gameObject);
}
}
Also you should not use Collision as your class name since Unity also uses it. Rename your script to something like CollisionScript.
i do not know why its not working here are some pictures 

There is no collider on your player object. Add a collider to your player object and it will work.
Your answer