1

I followed a tutorial on "How to make a video game" by Brackeys and I changed a few things but still copied most of what he did. After I copied his code on collision (episode 9) I got an error when my player crashed into another car saying "Null Reference Exception".

I tried looking up solutions online and making sure I did it right but its all confusing and idk.

using UnityEngine;

public class ColiisionScript : MonoBehaviour
{

    public forward movement;

    void OnCollisionEnter(UnityEngine.Collision collisionInfo)
    {
        if (collisionInfo.gameObject.tag == "StrangerThings")
        {
            GetComponent<forward>().enabled = false;                         
            FindObjectOfType<GameManager>().EndGame(); 
        }
    }
}

I wanted my game to restart a few seconds after the player hits an obstacle or another car but instead, the game pauses and tells me I have an error.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Justin Y.
  • 19
  • 2
  • 1
    Both GetComponent and FindObjectOfType might not find anything matching their conditions. At wich point you wrote null.enabled or null.EndGame() And while the null is of the proper type, it is still is not a very sensible order to call a instane function on what is not a instance. – Christopher Jul 27 '19 at 19:26
  • Which line is this error occuring on? and what steps have you done to troubleshoot it? It's cool you did research but what debugging did you do? Did you verify the object you are getting the null reference on actually exists? – AresCaelum Jul 27 '19 at 19:39
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Dour High Arch Jul 27 '19 at 19:44

1 Answers1

1

Put the GetComponent and FindObjectOfType calls into Forward and GameManager variables respectively.

forward f = GetComponent<forward>();
GameManager gm = FindObjectOfType<GameManager>();

Then check to see if they have values before calling the functions.

if(f != null)
  f.enabled = false;

if(gm != null)
  gm.EndGame();

//or a trick to shorten the code 

gm?.EndGame();