Different Approach

Instead of the collision handler to handle the scene reload, I created a new Game Object called GameManager and attached the GameManager script file. This leverages c# events to propagate when a player collision occurs. The one thing I did catch was the Player object was being destroyed before the on disable was occuring.

public class CollisionHandler : MonoBehaviour
{
    public event Action onPlayerCollision;

    private void OnTriggerEnter(Collider other) 
    {
        Debug.Log(this.name + "--Triggered with--" + other.gameObject.name); 

        if(this.tag == "Player" && other.tag == "Enemy")
        {
            if (onPlayerCollision != null)
            {
                onPlayerCollision();
            }
        }   
    }
}

Update to

public class GameManager : MonoBehaviour
{
    [SerializeField] GameObject player;
    
    [SerializeField] float timeToResetLevel = 1f;

    private void OnEnable() {
        player.GetComponent<CollisionHandler>().onPlayerCollision += ResetGame;
    }

    private void OnDisable() {
        if (player != null)
        {
            player.GetComponent<CollisionHandler>().onPlayerCollision -= ResetGame;
        }
    }

    private void ResetGame()
    {
        StartCoroutine(GameEnding());
    }

    private IEnumerator GameEnding()
    {
        yield return new WaitForSeconds(timeToResetLevel);

        player.GetComponent<CollisionHandler>().onPlayerCollision -= ResetGame;

        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
 
    }
}

Update to Player Controls to register to the event of a player collision.

    private void OnEnable()
    {
        GetComponent<CollisionHandler>().onPlayerCollision += DisablePlayer;
    }

    private void OnDisable()
    {
        GetComponent<CollisionHandler>().onPlayerCollision -= DisablePlayer;
    }

    private void DisablePlayer()
    {
        this.enabled = false;
    }
2 Likes

Awesome job :fire:

Privacy & Terms