Aromatic Arthur
Aromatic Arthur

Reputation: 1

I'm getting a null reference Exception in my collider 2D in Unity 2D

so I'm making a flappy bird game, but with the exception, that the player only dies if he hits the back wall. If he hits the wall, it should access a function inside my GameManager (empty object), which relads the scene.

public void OnTriggerEnter2D(Collider2D Doom)
    {
        Debug.Log("Collider works");
        GetComponent<GameManager>().EndGame();
    }

In this case, Doom is the back wall. When I run the game, I get an error NullReferenceException: Object reference not set to an instance of an object.

Could you help me out?

Upvotes: 0

Views: 1012

Answers (1)

sakaibats
sakaibats

Reputation: 36

A NullReferenceException happens when you are pointing towards something that is null. In your case, GetComponent().EndGame() is null.

Like what imserhane mentioned, when you are using GetComponent<>() you are trying to retrieve component from the gameobject this script is attached to. In your case, the two scripts are probably attached to different gameobject.

What you can do instead, is use FindObjectOfType, like what Iggy mentioned. The only thing is that instead of calling FindObjectOfType every time OnTriggerEnter2D is called, you can save a reference to your gameManager so it's more optimized. In this game, it probably doesn't matter but it's a good practice to do so.

This is how you do it.

GameManager gameManager;

// Save a reference to your GameManager
void Awake()
{
    gameManager = FindObjectOfType<GameManager>();
}

// Modify your code like this
public void OnTriggerEnter2D(Collider2D Doom)
{
    Debug.Log("Collider works");
    gameManager.EndGame();
}

If you would like to learn more about NullReferenceException, you can check out this video that explains the error in detail with examples, hope this helps!

Upvotes: 0

Related Questions