I am making an infinite runner game, and I am having issues with killing and respawning the player. I have a coroutine setup on the GameMaster objec which is the respawn and on the player I have a method that calls that coroutine. But when ever the player hits an enemy I get a Null Reference Exception and I am not sure why this is happining.
Here is the entire error
NullReferenceException: Object reference not set to an instance of an object Player.OnCollisionEnter2D (UnityEngine.Collision2D col) (at Assets/Script/Player.cs:32)
Here is the line that when I double click on the error it goes to. This line is on the player.
StartCoroutine(GetComponent<GameMaster>().RespawnPlayer());
This is the method that the above line is in. This method is on the player.
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Enemy")
{
Debug.Log("HIT");
Destroy(col.gameObject);
StartCoroutine(GetComponent<GameMaster>().RespawnPlayer());
}
}
Here is the coroutine that the above method is trying to call. This method is on the GameMaster GameObject and this object never gets destoryed or setActive false.
public IEnumerator RespawnPlayer()
{
player.GetComponent<SpriteRenderer>().enabled = false;
player.GetComponent<BoxCollider2D>().enabled = false;
player.GetComponent<movemnt>().enabled = false;
yield return new WaitForSeconds(respawnDelay);
adMenu.SetActive(true);
}
If anybody can give any suggestions that would be great!