Script inside prefab can't access another script

I’m currently trying to make a Sudoku game, and I want to get a variable in a script that’s inside a canvas. The script I’m trying to access it from is in a prefab.
This is the code in the prefab:

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

public class GridButtonHandler : MonoBehaviour, ISelectHandler
{
    
    Grid gridScript;

    // Start is called before the first frame update
    void Start()
    {
        gridScript = GetComponent<Grid>();
        //Button btn = button.GetComponent<Button>();
        //btn.onClick.AddListener(OnClick);
    }

    public void OnSelect(BaseEventData eventData)
    {
        int selectedButton = int.Parse(gameObject.transform.parent.name);
        Debug.Log(selectedButton);
        gridScript.selectedSquare = selectedButton;
    }

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

However, this error occurs: NullReferenceException: Object reference not set to an instance of an object
I’ve tried many different answers I found on the web but nothing works.

Assuming your trying to get gridScript. It has an internal access modifier variable by default.
See more information here: Access Modifiers - C# Programming Guide | Microsoft Learn

There are a few things you could do. The simple thing is to make the variable public.

     public class GridButtonHandler : MonoBehaviour, ISelectHandler
     {
         
         public Grid gridScript; // freely accessible
    ...
    }

The other way is to have setters and getters, which allows you to control how to set the variable and how to give the variable out. The both MUST be public in order for them to be accessed outside the class.

 public class GridButtonHandler : MonoBehaviour, ISelectHandler
 {
     
     Grid gridScript;
...
     public void setGridScript(Grid grid) // setter method
     {
          gridScript = grid;
     }

     public Grid getGridScript() // getter method
     {
          return gridScript;
     }
}

This page on the importance of setters and getters is for Java but easily translates to any programming language, especially C#.


If you are not trying to access gridScript, please let me know what you are trying to access!