NullReferenceException when using variable from other script

I’m getting this error when I run my game:
NullReferenceException: Object reference not set to an instance of an object
ChoiceButtons.selectedThisAnswer () (at Assets/Scripts/ChoiceButtons.cs:23)

Does anyone know why this is happening? Here are the two scripts:

    public class ChoiceButtons : MonoBehaviour {

    // Each button needs to have an ID so that we know which one they pressed
    // as well as what to assign it. 


    [SerializeField] int choiceId;
    [SerializeField] TextMeshProUGUI choiceText;
    public int wrong = 0;
    public GameManager gameManager;
    GameoverScript gameover;

    public void selectedThisAnswer(){
        Debug.Log("Selected: " + choiceId);
        //Do things with score and winning etc
        **_if (choiceId == gameManager.randomChoiceButtonIDAsWinner)_**
        {
            Debug.Log("Correct");
            Object.FindObjectOfType<GameManager>().ShowNewQuestion();

        }
        else
        {
            Debug.Log("Wrong");
            switch (wrong)
            {
                case 0:
                    Image heart3 = GameObject.Find("heart3").GetComponent<Image>();
                    heart3.enabled = false;
                    wrong = 1;
                    break;
                case 1:
                    Image heart2 = GameObject.Find("heart2").GetComponent<Image>();
                    heart2.enabled = false;
                    wrong = 2;
                    break;
                case 2:
                    Image heart1 = GameObject.Find("heart1").GetComponent<Image>();
                    heart1.enabled = false;
                    gameover.Gameover();
                    wrong = 3;
                    break;
            }
            Object.FindObjectOfType<GameManager>().ShowNewQuestion();
        }
        //start new questions
        //Object.FindObjectOfType<GameManager>().ShowNewQuestion();
         

    }


    public int GetChoiceId(){
        return choiceId;
    }

    public TextMeshProUGUI GetChoiceText()
    {
        return choiceText;
    }
}
    public class GameManager : MonoBehaviour {

    // This is the question's text
    [SerializeField] TextMeshProUGUI questionText;

    // This is the container that holds all of the choices. I've put this here so that we can loop through each button later
    [SerializeField] GameObject choices;


    public bool correct;

    // these are the questions. I've labeled them like this so its easier to debug what the right answers are
    string[] questions = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };

    // These are going to be the answers. We could also combine these two arrays and make a dictionary instead. For now this will be fine though.
    string[] answers = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };

    // This is going to hold our randomly selected question's position
    int randomAnswerPositionInArray;

    // This is going to hold our randomly selected choice button that is the winner
    public int randomChoiceButtonIDAsWinner;

    //Create an array to hold all of the answers. We are going to use this array to populate the choice text.
    string[] textForChoiceButtons;

	// Use this for initialization
	void Start () {

        ShowNewQuestion();

	}



    public void ShowNewQuestion(){
        // Pick a random question
        randomAnswerPositionInArray = UnityEngine.Random.Range(0, questions.Length - 1);

        //Update the question's text
        questionText.text = questions[randomAnswerPositionInArray];

        //Choose a random button as the correct choice
        randomChoiceButtonIDAsWinner = UnityEngine.Random.Range(0, 3);
    }

There’s more but it’s not relevant. Thanks

Hi,

Could you post the first script in it’s entirity, as at the moment line 23 appears to be an opening brace and as such doesn’t make any sense in relation to your error message.

Could you also please apply code formatting, thanks :slight_smile:


See also;

The only thing I forgot to have in the ChoiceButtons Script was the last ‘}’. Everything else there is all there is

Ok, well in that case your error message doesn’t align with a NullReferenceException. Perhaps you could indicate which line the error is on? e.g. post the line of code for the error.

I suspect it’s about 4 lines out, due to the missing using directives at the top of your code.

In the first script, it is the beginning of the if statement for the selectedThisAnswer() function. There are now _ _ on either side

if (choiceId == gameManager.randomChoiceButtonIDAsWinner)

Ok, so gameManager is the object in this case, you could do a quick test before this statement to see if this object is null just to be certain, e.g. output something to console.

Assuming it is, have you remembered to drag your GameManager GameObject from the Hierarchy to the exposed Game Manager field on the ChoiceButtons.cs script component?

As a side note, all of your subsequent Find calls are quite expensive from a performance perspective, as you have already got a reference to the GameManager GameObject, via, gameManager, why not use it? e.g.

gameManager.ShowNewQuestion();

instead of;

Object.FindObjectOfType<GameManager>().ShowNewQuestion();

(and all of the other subsequent calls to Find)

Would I be correct in assuming your serialized ‘choices’ GameObject in GameManager is, in the end, just your ChoiceButtons script?

If it is, a refactor is likely your best option. Circular references are bad voodoo. That is, children should not reference and call against their parent objects. I’m guessing you could also go the performance hit route of using [… public GameManager gameManager = Object.FindObjectOfType(); …] for your declaration to point at the active GameManager (at least based on what I just read about the subject in Unity docs, that’s an untested theory at best).

Disclaimer: I’m still not very familiar with Unity, so a lot of the behind the scenes work it does is still something of an enigma.

EDIT: Forgot about the angle braces issue, declaration would be:

public GameManager gameManager = Object.FindObjectOfType<GameManager>();

Privacy & Terms