Getting an error that coroutine can't be started on an inactive object, but the object is active

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?

I described here why you have to avoid coding like this.

Anyway, a few comments on the current code:

  • line 22: you can leave just else without condition.
  • line 30: gm = this again (why?), but for every object. Are you confident that Start() is not called after destroying? Check it with Debug.Log.

Destroying the gameObject inside the component on it will cause issues anyway. After that, the code in one place will be stopped (maybe not right away), in the other place you will get an error like yours, or a null reference exception, or others.