Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Trying to access a class outside of file but getting Object reference error

Discussion in 'Scripting' started by hqhaven, Dec 8, 2022.

  1. hqhaven

    hqhaven

    Joined:
    Nov 29, 2022
    Posts:
    2
    Hello,
    I'm trying create a global class that I can access and modify from outside of the script but I keep getting this error:
    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. GridSystem.Start () (at Assets/Scripts/Grid/GridSystem.cs:45)
    Here's the code of the class:

    Code (CSharp):
    1. using System.Collections;
    2.     using System.Collections.Generic;
    3.     using UnityEngine;
    4.  
    5.     [System.Serializable]
    6.     public class GridManager : MonoBehaviour
    7.     {
    8.         private static GridManager _gridManager;
    9.         public static GridManager Instance { get { return _gridManager; } }
    10.         void Awake()
    11.         {
    12.             _gridManager = this;
    13.         }
    14.  
    15.         public GridSlot[] allGrids = new GridSlot[10100];
    16.  
    17.         public void AddGridSlot(int id, Vector3 pos)
    18.         {
    19.             allGrids[id]            = new GridSlot();
    20.             allGrids[id].id         = id;
    21.             allGrids[id].position   = pos;
    22.             allGrids[id].leftSlot   = id - 1;
    23.             allGrids[id].rightSlot  = id + 1;
    24.             allGrids[id].aboveSlot  = id + 100;
    25.             allGrids[id].leftSlot   = id - 100;
    26.             allGrids[id].beingUsed  = false;
    27.         }
    28.     }
    And here's the code where I'm trying to use the class instance outside of the file:
    Code (CSharp):
    1.   GridManager.Instance.AddGridSlot(i, new Vector3(curX, max.y, curZ));
    Thanks for the help
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    Assuming
    GridManager.Instance.AddGridSlot(i, new Vector3(curX, max.y, curZ));
    is line 45 of GridSystem.cs then it stands to reason you simply don't have a GridManager in your scene.
     
  3. hqhaven

    hqhaven

    Joined:
    Nov 29, 2022
    Posts:
    2
    I don't know why I thought I didn't have to actually add it to the scene. That fixed it.

    Thanks