NullReferenceException

Hi, I’m really new to game development and coding in general. But I am getting a NullReferenceException Error on my Number Wizard Game.

Here’s my code:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class NumberWizard : MonoBehaviour
{
    int max;
    int min;
    int Guess;
    int maxguesses = 10;

    public Text text = null;
    public Text lguess = null;

    // Use this for initialization
    void Start()
    {
        StartGame();
        NextGuess();
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void GuessHigher()
    {
        min = Guess;
        NextGuess();
    }

    public void GuessLower()
    {
        max = Guess;
        NextGuess();
    }


    void StartGame()
    {
        max = 1002;
        min = 0;
    }

    void NextGuess()
    {
        Guess = Random.Range(min, max);
        text.text = Guess.ToString();
        guessleft();
        if (maxguesses <= 0)
        {
            Application.LoadLevel("Win");
        }

    }

    void guessleft()
    {
        maxguesses = maxguesses - 1;
        lguess.text = maxguesses.ToString();
    }
}

And here’s the errors:

NullReferenceException: Object reference not set to an instance of an object
NumberWizard.NextGuess () (at Assets/NumberWizard.cs:50)
NumberWizard.Start () (at Assets/NumberWizard.cs:19)

NullReferenceException: Object reference not set to an instance of an object
NumberWizard.guessleft () (at Assets/NumberWizard.cs:62)
NumberWizard.NextGuess () (at Assets/NumberWizard.cs:51)
NumberWizard.Start () (at Assets/NumberWizard.cs:19)

Sorry if this is a noob question. And please keep your answer close to layman’s term as possible, I’m still learning all the technical terms. :slight_smile:

  • When an an object is not given a value it has the value of “null”.
  • If you attempt to use anything with a value of “null” you will get a “NullReferenceException”.

In the first error you areattempting to use a integer called"Guess". The problem is you haven’t given “Guess” a value. In the 2nd error you try to use “lguess” which has a null value. A good way to counter this problem is if you check if a value is null before you use it.
Ex:

if(objectBeingUsed == null)

or always initializing values i.e:

int Guess = 0;