What you could do is create a function on the player that is called whenever the player is supposed to die (so you can call the function from anywhere and don’t have to duplicate code for different things that kill the player). If you would like you could just reload the scene when the player dies (it would reset everything as if you had just loaded it for the first time). Depending on the type of game you’re making, this is probably the best solution unless you want to keep certain variables or objects after the player dies. That would look something like this:
using UnityEngine.SceneManagement;
public void Die()
{
SceneManager.LoadScene(SceneManager.GetActiveScene);
}
If you wanted everything except for the player to remain how it was (like if you wanted enemies to stay dead or whatever), you could reset just the player back to their original position or to a GameObject you’ve created. So if you were doing it with a coordinate, it would look something like this:
//We use a variable instead of defining it in the script so we can edit the position from the inspector.
public Vector3 respawnPosition = new Vector3(0,0,0)
public void Die()
{
transform.position = respawnPosition;
}
Then if we were doing it to a GameObject, we would want to be able to get a reference to it somehow. So for this example, give the respawn position GameObject a tag (for this example, I’ll use “RespawnPosition”). Then, the script would look something like this:
public void Die(
{
transform.position = GameObject.FindGameObjectWithTag("RespawnPosition").transform.position;
//Or...
Vector3 respawnPosition = GameObject.FindGameObjectWithTag("RespawnPosition").transform.position;
transform.position = respawnPosition;
}
Then on whatever kills the player, you just need to call that function. So for example on your red box, you would do something like this:
void OnCollisionEnter2D(Collision2D col)
{
col.GetComponent<ScriptName>().Die();
}
This will call Die(), and whatever option you chose to do will be done.
Let me know if you have any other questions and good luck on your game dev journey!