# NullReferenceException Error For Respawning [duplicate]

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);
}


If anybody can give any suggestions that would be great!

• Are you sure the object has a gamemaster component? – Bálint Apr 26 '18 at 7:23

First of all instead of using such tag comparison use

gameObject.CompareTag("Enenmy")


This is just an input to avoid GC.

Public static GameMaster Instance;
void Awake()
{
Instance = this;
}


Then in your script jus use

StartCoroutine(GameMaster.Instance.RespawnPlayer());


Using this your GameMaster will always be available for you no need to call GetComponent or FindObjectOfType to find it you just need to call GameMaster.Instance.YourMethodOrVariable. Hope this will help

• While most likely a solution, it does not explain the root cause of the problem much (see the answers of the duplicate). Moreover it is discouraged to answer duplicate/offtopic questions. – wondra Apr 26 '18 at 19:08
• Thanks so much for responding! What you suggested did work!! – C. Smith Apr 26 '18 at 22:03