0
\$\begingroup\$

This question already has an answer here:

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!

\$\endgroup\$

marked as duplicate by DMGregory unity Apr 26 '18 at 15:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    \$\begingroup\$ Are you sure the object has a gamemaster component? \$\endgroup\$ – Bálint Apr 26 '18 at 7:23
0
\$\begingroup\$

First of all instead of using such tag comparison use

gameObject.CompareTag("Enenmy")

This is just an input to avoid GC.

Answer

Use Singleton for your GameMaster object add these lines of code

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – wondra Apr 26 '18 at 19:08
  • \$\begingroup\$ Thanks so much for responding! What you suggested did work!! \$\endgroup\$ – C. Smith Apr 26 '18 at 22:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.