Search code examples
c#unity-game-enginetimedelay

unity respawn after delay


I'm trying to respawn an object at "x" amount of time however when i use yield and startcourutine it causes a lot of errors and mistakes in my code. and instead of destroying i want to hide the object and enable it again when i respawn it after the delay. how is this possible if i have arrays?


Solution

  • For a direct respawn on the same position you can do this:

    public class CrateCrash : MonoBehaviour
    {
        ...
    
        public void InitRespawn(GameObject toRespawn)
        {
            StartCoroutine(RespawnObject(toRespawn, 5.0f));
        }
    
        private IEnumerator RespawnObject(GameObject toRespawn, float delay)
        {
            yield return new WaitForSeconds(delay);
            toRespawn.SetActive(true);
        }
    }
    

    The other class:

    using UnityEngine;
    using System.Collections;
    
    
    public class Crate : MonoBehaviour
    {   
        CrateCrash manager;    
    
        public void OnMouseDown()
        { 
            manager.InitRespawn(gameObject);
    
            gameObject.SetActive(true);
    
        }
    
        public void SetManagerReference(CrateCrash managerRef)
        {
            manager = managerRef;
        }    
    }