'I am getting a NullReferenceException with unity collisions [duplicate]

This is my code that is receiving the error on the playerScore increment line. The code is in a prefab that is generated many times, and if it hits the player, it is destroyed and the player's score is incremented. Currently the code will destroy on collision with anything that does not have the name "Player" due to the error once the if statement is executed.

private void OnCollisionEnter2D(Collision2D collisionInfo)
    {
        
        
        Debug.Log($@"Collision name = {collisionInfo.collider.name}");
        
        if (collisionInfo.collider.name == "Player")
        {
            GetComponent<GameMechanics>().playerScore++;

        }

       
        GameObject e = Instantiate(explosion) as GameObject;
        e.transform.position = transform.position;
        Destroy(gameObject);
    }

This is my code for the referenced variable, I just cannot tell what I am doing wrong here, I want the object destroyed in all cases, but want the score incremented when the player hits it.Is the object being destroyed preventing the changes to be made to the player score?

public class GameMechanics : MonoBehaviour
{
   public int playerScore;
   // Start is called before the first frame update
   void Start()
   {
       playerScore = 0;
   }

   // Update is called once per frame
   void Update()
   {
       
       Debug.Log($@"Player Score = {playerScore} ");

   }
}

Thanks in advance!



Solution 1:[1]

This is because you are using GetComponent in a class that does not have it and should find GameMechanics in it, but the result is null.

GetComponent<GameMechanics>().playerScore++; // GameMechanics dosen't found..


One way is to give GameMechanic to the other object's is through the inspector:

public GameMechanics Mechanics;
private void OnCollisionEnter2D(Collision2D collisionInfo)
{
    if (collisionInfo.collider.name == "Player") Mechanics.playerScore++;
}

However There are other ways to reference GameMechanic and Manager classes in other objects, the best of which is Singleton. here is a simple way to solve your problem easy and that is to use FindObjectOfType. Change the code below and it will probably be fixed.

if (collisionInfo.collider.name == "Player")
{
    FindObjectOfType<GameMechanics>().playerScore++; // replace it with this way
}

Solution 2:[2]

NullReferenceExceptions occur when the code attempts to access a variable which has not been initialized properly. In your case, this could be because of several reasons.

Ensure the gameobject is set to active in the scene Ensure the script object is enabled on the gameobject

If these do not help, you can try making your variable static, and setting it to an ititial value of 0.

Static variables are loaded before everything else, and accessible by most other classes, so this may be able to fix your issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KiynL
Solution 2 JensenMcKenzie