- Home /
how to respawn with a simple delay?
using UnityEngine; using System.Collections;
public class Respawn : MonoBehaviour {
// Use this for initialization
public GameObject other;
void OnTriggerEnter2D (Collider2D other) {
if (other.gameObject.tag == "Car1") {
transform.position = new Vector3 (0f,0f,0f); //<---wanted to respawn to this position
}
}
}
Answer by nightowl79a · Jan 26, 2015 at 12:09 PM
The way I would do it is make the player into a prefab. Make an empty gameobject where you want to player to respawn. Then add a script like this to the object that triggers the player death:
public GameObject carl;
public Transform spawnPoint;
void OnTriggerEnter(Collider other)
{
if (other.tag == "Carl")
{
Destroy(other.gameObject);
StartCoroutine("Respawn", 5f);
}
}
IEnumerator Respawn(float spawnDelay)
{
yield return new WaitForSeconds(spawnDelay);
Instantiate (carl, spawnPoint.position, spawnPoint.rotation);
}
You see, when the player hits the trigger I destroy the player and respawn him from a prefab, using the IEnumerator. If you need to player to keep data then instead of destroying him you can just disable his gameobject in the trigger event, and then re-enable it in the IEnumerator.
"if you need the player to keep data then instead of destroying him you can just disable his game object in the trigger event, and then re-enable it in the IEnumerator". Can you please explain with same example. Thank you.
https://docs.unity3d.com/ScriptReference/GameObject.SetActive.html other.gameobject.setactive(false)
setting active to false keeps the game object in the scene, but makes it almost gone, no render, or colliders, or anything like that, and variable's set in scripts like maybe HP for example stay the same, unlike gameobject.destroy, witch removes it from the scene completely.
What does the value "5f" in the parameters of the StartCoroutine function do? If it's the amount of time it will delay, then how does it connect to the parameter "spawnDelay" in the Respawn function?
Take a look at the documentation
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
The second argument of StartCoroutine
using a string will be passed to the actual coroutine method.
Today, it's highly advised to use the following way to start a coroutine.
StartCoroutine(Respawn(5f));
f is for float. all floats require "f" in front of them. I guess I should have used a variable instead, but it was just a quick write.
Your answer
![](https://koobas.hobune.stream/wayback/20220613181532im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
What to do with Player game object while he is waiting to respawn. 1 Answer
How to delay a respawn? 1 Answer
Dealing with nulls on Respawn 1 Answer
Fade on death! 1 Answer