- Home /
C# help with Player Death on Collision with Tag
I'm a beginner in Unity but I'll try my best explaining my problem.
I have a simple platformer I'm trying to build, and I have trouble wrapping my head around the collision/collider code in C# (I found a lot of forums answering this question, but mostly in JS)
Basically, on collision with the enemy, which have "Death" tags, I want the player sprite to spawn back at the beginning of the scene (similar to an Application.loadlevel). I'm having trouble forming that actual code of OnCollision with "Death" tag --> Application.loadlevel("LevelName"); - that's to the extent that I understand it, but writing the code in between is where I'm getting lost.
I would appreciate any help, I'm only running across JS answers and feel really stuck.
Answer by MUGIK · Jul 12, 2016 at 11:48 AM
void OnCollisionEnter(Collision other)
{
if (other.collider.CompareTag("Death"))
Respawn();
}
void Respawn(){
transform.position = Vector3.zero;
}
But I advise u using Triggers and OnTriggerEnter(Collider other) instead of OnCollisionEnter(Collision other) (its about performance). See this tutor: https://unity3d.com/ru/learn/tutorials/topics/physics/colliders-triggers
Answer by DenisTribouillois · Jul 12, 2016 at 11:47 AM
Hello, you should try something like this.
Create a new script:
public class CollisionDetector : MonoBehaviour {
void OnCollisionEnter(Collision col)
{
if (col.gameObject.tag == "Death")
{
SceneManager.LoadScene("LevelName");
}
}
}
And attach this script to your player.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
how do i make an Enemy take damage from prefab bullet clone? 1 Answer
Destroy object on touch of object with specific class 3 Answers
Distribute terrain in zones 3 Answers
Sound plays right at the beginning 2 Answers