0

When the time exceeds the max, it spams me with NullReferenceException errors. I can't seem to figure out why it would give me this error. The errors happen on the same lines of code, both of which being the nested if statements. It's probably the scene.score but score is defined within the PlayerScript script.

public int timeLimit = 15;
public float startTime = 0;

PlayerScript scene = GetComponent<PlayerScript>();
    if (startTime >= timeLimit)
    {
        if (scene.score >= 25)
        {
            SceneManager.LoadScene("WinScene");
        }
        if (scene.score < 25)
        {
            SceneManager.LoadScene("LoseScene");
        }
    }  

EDIT
when I test it in Unity, after the time exceeds 15 seconds, it gives me errors telling me that it is on a certain line of code. That being the first nested if statement. I commented out that first one and left the second one to test, and sure enough it told me that this new line was causing the error.

EDIT
Looks like switching GetComponent with FindObjectOfType did the trick. <PlayerScript> is a different script that I was trying to pull info from, ie. score.

Nick G
  • 23
  • 3
  • It sounds like `GetComponent()` is returning null. Are you sure `PlayerScript` is a component of this script's GameObject? – Serlite Feb 01 '17 at 06:41
  • Are you sure your `SceneManager` is not null? One way is to add breakpoints inside both your if loops (which by the way could be If..Else for clarity) and check what is causing the Exception. – Keyur PATEL Feb 01 '17 at 06:45
  • @KeyurPATEL In this case, it's unlikely `SceneManager` is null - it's one of the classes available in the Unity libraries. (It's a static method being called anyways, so it doesn't need an instance.) – Serlite Feb 01 '17 at 06:46
  • Since I am picky and like reducing lines, if you resolve the NullReferenceException you could simple use this line: `if (startTime >= timeLimit) { SceneManager.LoadScene((scene.score < 25) ? "LoseScene" : "WinScene") }` since the score is either below 25, or 25 & above, there is no other case. – Keyur PATEL Feb 01 '17 at 06:47
  • @Serlite Then you're right, it is most probably the `GetComponent()` which returns null. – Keyur PATEL Feb 01 '17 at 06:48

0 Answers0