0

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!

  • Which game object did you connect GameMechanic to? – KiynL May 16 '22 at 06:09
  • @KiynL It is attached to an empty object that I created to hold the scripts for the game to run. Could the empty object be the issue? – The Feesher May 16 '22 at 06:14
  • I think I found the problem. I will answer in the answer section. – KiynL May 16 '22 at 06:19
  • @madreflection informative for sure, I think a bit over my head at the moment unfortunately, Im sure the answer is in there in some way or another lol but from what I saw, I didn't see anything that stood out to me. Thank you though! – The Feesher May 16 '22 at 06:23
  • GetComponent searches for the Component on the current game object. If GameMechanics is attached to some "Manager" concept, then you won't find it on this colliding object. You need to get the game object, best by tag, and then GetComponent on it. – Everts May 16 '22 at 06:27
  • You need to get it *under* your head before moving forward. These answers will tell you about *this* exact situation, but until you can use the debugger to find what's null, and then read the appropriate documentation to understand why, you're going to be asking about this exception again and again. – madreflection May 16 '22 at 06:41
  • At the very least, you should be able to tell us from the start that `GetComponent` is returning `null`. Until you can figure that much out on your own, keep reading that linked article. – madreflection May 16 '22 at 06:43

2 Answers2

0

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
}
KiynL
  • 4,097
  • 2
  • 16
  • 34
  • I do not fully understand, I am still very new, but this solved it! I will read over this some more when I am less tired and frustrated lol Is it because the script I am referencing is not apart of the same object?? – The Feesher May 16 '22 at 06:48
  • @TheFeesher It means almost the same thing. GetComponent can only get the component to which you are attached to the object. If you want to get from another object, you must first reference it like someObject.GetComponent ... – KiynL May 16 '22 at 06:52
-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.

  • State is enabled, and the script is enabled. I tried to set the variable to static, but then unity gave me a compile error for the variable being inaccessible due to protection level :/ – The Feesher May 16 '22 at 06:20