I’m making a simple 2d game in unity that’s similar to Galaga. To make the respawn mechanic, when the player instance is destroyed, it starts a coroutine that waits 3 seconds, then instantiates a new player object. However, whenever the player is hit and destroyed, I get an error saying the coroutine can’t be started because the game manager object is inactive. I have 9 idea how to fix this, as the game manager is always active, and there is nothing in any script that would deactivate it.
My code for the game manager is
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
private static GameManager gm;
//player stuff
public GameObject player;
public int score;
private void Awake()
{
if(gm == null)
{
gm = this;
DontDestroyOnLoad(this);
}
else if (gm != this)
{
Destroy(gameObject);
}
}
// Start is called before the first frame update
void Start()
{
gm = this;
Instantiate(player);
}
// Update is called once per frame
void Update()
{
}
public void HasBeenHit() //this bit goes over everything that happens when the player is hit by a bullet and dies
{
Debug.Log("Player was killed");
StartCoroutine(WaitForRespawn());
}
IEnumerator WaitForRespawn()
{
yield return new WaitForSeconds(3);
Instantiate(player);
}
}
When the player object is destroyed, it calls the HasBeenHit function before destroying itself. Can anyone help me with this?