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.

2 Answers

2

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: 3D Physics - Unity Learn

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.