Object reference not set to an instance of an object

Here is the code:
GridSpace.cs:

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

public class GridSpace : MonoBehaviour
{
    public Button button;
    public Text buttonText;

    private GameController gameController;
    public void Set()
    {
        buttonText.text = gameController.GetplayerSide();
        button.interactable = false;
    }
   
    public void SetgameController(GameController controller)
    {
        gameController = controller;
    }
}

GameController.cs:

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

public class GameController : MonoBehaviour
{
    public Text[] buttonList = new Text[9];
   
    void SetgameControllerOnButtons()
    {
        for (int i = 0; i < buttonList.Length; i++)
            buttonList[i].GetComponentInParent<GridSpace>().SetgameController(this);

    }
    void Init()
    {
        SetgameControllerOnButtons();
    }
    public string GetplayerSide()
    {
        return "1";
    }
}

I get this error on line 14:
NullReferenceException: Object reference not set to an instance of an object
GridSpace.Set () (at Assets/Scripts/GridSpace.cs:14)

I can’t see what’s wrong… Telling me what to fix would be great! Also explaining me what’s the issue in my code would be much appreciated.

P.S: I just started to work in Unity.

It’s trying to tell you you’re trying to do something with something that doesn’t exist. For this one it’s either telling you you’re trying to call GetComponentInParent on an object that doesn’t exist, or you’re trying to call SetgameController on an object that doesn’t exist. So check that your buttonList Text references are all set in the inspector, then check to make sure there’s definitely a GridSpace attached to a GameObject in it’s parent hierarchy. Lastly make sure the GridSpace’s GameObject is turned on in the scene and not greyed out or something.

Thank you for answering!
Everything was alright. I fixed it by changing void Init() to void Awake(). I really dont know why it works now, but it works.

Edit: I’ve done some research and now i know that Awake() is acting like a constructor. You were right, i was trying to do something with something that doesnt exist, haha.

1 Like