Search Unity

Question I'm getting error "NullReferenceException: Object reference not set to an instance of an object"

Discussion in 'Scripting' started by IceCubeInk, Jun 4, 2023.

  1. IceCubeInk

    IceCubeInk

    Joined:
    Nov 25, 2022
    Posts:
    2
    I'm very new to Unity and scripting, my first project is 3D Minesweeper game and it's almost done except I can't set or get a type of cell. It gives me 2 types of error, first when instantiating a grid and setting a type of "Mine" or an indicator of neighboring mines to cells, the second is when I try to get a cell type and instantiate a number prefab or when I try to mark a cell. The first error occurs at "BoxGridObject boxGridObject = Grid.GetBoxValue(x, y, z);" part and the second one at "BoxGridObject boxGridObject = Grid.GetBoxValue(hit.point);"

    Not all of the code is done, but here are the scripts:


    public class BoxGrid<TGridObj>
    {
    public static int Mine;
    public static int width;
    public static int height;
    public static int length;
    public float CellSize;
    public TGridObj[,,] BoxGridArray;
    private TGridObj BoxOpen;

    public BoxGrid(int width, int height, int length, float CellSize, int Mine) {
    Object BoxPrefab = Resources.Load("Box");

    BoxGrid<int>.Mine = Mine;
    BoxGrid<int>.width = width;
    BoxGrid<int>.height = height;
    BoxGrid<int>.length = length;
    this.CellSize = CellSize;

    BoxGridArray = new TGridObj[width, height, length];

    for (int x = 0; x < BoxGridArray.GetLength(0); x++) {
    for (int y = 0; y < BoxGridArray.GetLength(1); y++) {
    for (int z = 0; z < BoxGridArray.GetLength(2); z++) {
    GameObject.Instantiate(BoxPrefab, GetPosition(x, y, z) + new Vector3(CellSize, CellSize, CellSize) * 0.5f, Quaternion.Euler(-90, 0, 0));
    }
    }
    }
    }
    public void SetBoxValue(int x, int y, int z, TGridObj BoxOpen)
    {
    if (x >= 0 && x < width && y >= 0 && y < height && z >= 0 && z < length)
    {
    BoxGridArray[x, y, z] = BoxOpen;
    }
    }
    public void SetBoxValue(Vector3 WorldPosition, TGridObj BoxOpen)
    {
    int x, y, z;
    GetBoxPos(WorldPosition, out x, out y, out z);
    SetBoxValue(x, y, z, BoxOpen);
    }
    public TGridObj GetBoxValue(int x, int y, int z)
    {
    if (x >= 0 && x < width && y >= 0 && y < height && z >= 0 && z < length)
    {
    return BoxGridArray[x, y, z];
    }
    else
    {
    return default(TGridObj);
    }
    }
    public TGridObj GetBoxValue(Vector3 WorldPosition)
    {
    int x, y, z;
    GetBoxPos(WorldPosition, out x, out y, out z);
    return GetBoxValue(x, y, z);
    }
    public Vector3 GetPosition(int x, int y, int z)
    {
    return new Vector3(x, y, z) * CellSize;
    }
    private void GetBoxPos(Vector3 WorldPosition, out int x, out int y, out int z)
    {
    x = Mathf.FloorToInt(WorldPosition.x / CellSize);
    y = Mathf.FloorToInt(WorldPosition.y / CellSize);
    z = Mathf.FloorToInt(WorldPosition.z / CellSize);
    }
    }

    public class PlayMenu : MonoBehaviour
    {
    public Object MineObject;
    public GameObject Error;
    public GameObject GridCenter;
    public GameObject Camera;
    public TMP_InputField CWidth;
    public TMP_InputField CHeight;
    public TMP_InputField CLength;
    public TMP_InputField CMines;
    public TouchControl script;
    private BoxGrid<BoxGridObject> Grid;
    public BoxGridObject boxGridObject;
    public void Beginner()
    {
    Grid = new BoxGrid<BoxGridObject>(4, 4, 4, 25f, 8);
    boxGridObject = new BoxGridObject(Grid, 4, 4, 4);
    Camera.transform.position = new Vector3(4 * 25f / 2, 4 * 25f / 2, 150 + 4 * 25f);
    GridCenter.transform.position = new Vector3(4 * 25f / 2, 4 * 25f / 2, 4 * 25f / 2);
    script.distanceToTarget = 200f;
    PlayerPrefs.SetInt("ModeValue", 1);

    int MinesPlaced = 0;
    while (MinesPlaced < 8)
    {
    int x = Random.Range(0, 4);
    int y = Random.Range(0, 4);
    int z = Random.Range(0, 4);
    BoxGridObject boxGridObject = Grid.GetBoxValue(x, y, z);
    if(boxGridObject.GetCellType() != BoxGridObject.BoxType.Mined)
    {
    boxGridObject.SetCellType(BoxGridObject.BoxType.Mined);
    MinesPlaced++;
    }
    }
    for(int x = 0; x < Grid.BoxGridArray.GetLength(0); x++) {
    for(int y = 0; y < Grid.BoxGridArray.GetLength(1); y++) {
    for(int z = 0; z < Grid.BoxGridArray.GetLength(2); z++) {
    BoxGridObject boxGridObject = Grid.GetBoxValue(x, y, z);
    if(boxGridObject.GetCellType() == BoxGridObject.BoxType.Empty)
    {
    List<BoxGridObject> NeighbourList = GetNeighbours(x, y, z);
    int MineCount = 0;
    foreach(BoxGridObject Neighbour in NeighbourList) {
    if(Neighbour.GetCellType() == BoxGridObject.BoxType.Mined)
    {
    MineCount++;
    }
    }
    switch(MineCount)
    {
    case 1: boxGridObject.SetCellType(BoxGridObject.BoxType.num1); break;
    case 2: boxGridObject.SetCellType(BoxGridObject.BoxType.num2); break;
    case 3: boxGridObject.SetCellType(BoxGridObject.BoxType.num3); break;
    case 4: boxGridObject.SetCellType(BoxGridObject.BoxType.num4); break;
    case 5: boxGridObject.SetCellType(BoxGridObject.BoxType.num5); break;
    case 6: boxGridObject.SetCellType(BoxGridObject.BoxType.num6); break;
    case 7: boxGridObject.SetCellType(BoxGridObject.BoxType.num7); break;
    case 8: boxGridObject.SetCellType(BoxGridObject.BoxType.num8); break;
    case 9: boxGridObject.SetCellType(BoxGridObject.BoxType.num9); break;
    case 10: boxGridObject.SetCellType(BoxGridObject.BoxType.num10); break;
    case 11: boxGridObject.SetCellType(BoxGridObject.BoxType.num11); break;
    case 12: boxGridObject.SetCellType(BoxGridObject.BoxType.num12); break;
    case 13: boxGridObject.SetCellType(BoxGridObject.BoxType.num13); break;
    case 14: boxGridObject.SetCellType(BoxGridObject.BoxType.num14); break;
    case 15: boxGridObject.SetCellType(BoxGridObject.BoxType.num15); break;
    case 16: boxGridObject.SetCellType(BoxGridObject.BoxType.num16); break;
    case 17: boxGridObject.SetCellType(BoxGridObject.BoxType.num17); break;
    case 18: boxGridObject.SetCellType(BoxGridObject.BoxType.num18); break;
    case 19: boxGridObject.SetCellType(BoxGridObject.BoxType.num19); break;
    case 20: boxGridObject.SetCellType(BoxGridObject.BoxType.num20); break;
    case 21: boxGridObject.SetCellType(BoxGridObject.BoxType.num21); break;
    case 22: boxGridObject.SetCellType(BoxGridObject.BoxType.num22); break;
    case 23: boxGridObject.SetCellType(BoxGridObject.BoxType.num23); break;
    case 24: boxGridObject.SetCellType(BoxGridObject.BoxType.num24); break;
    case 25: boxGridObject.SetCellType(BoxGridObject.BoxType.num25); break;
    case 26: boxGridObject.SetCellType(BoxGridObject.BoxType.num26); break;
    }
    }
    }
    }
    }
    }
    private List<BoxGridObject> GetNeighbours(int x, int y, int z)
    {
    List<BoxGridObject> NeighbourList = new List<BoxGridObject>();

    if (z - 1 >= 0)
    {
    //back
    NeighbourList.Add(Grid.GetBoxValue(x, y, z - 1));
    if (x - 1 >= 0)
    {
    //back left
    NeighbourList.Add(Grid.GetBoxValue(x - 1, y, z - 1));
    //back left down
    if(y - 1 >= 0) NeighbourList.Add(Grid.GetBoxValue(x - 1, y - 1, z - 1));
    //back left up
    if(y + 1 < Grid.BoxGridArray.GetLength(1)) NeighbourList.Add(Grid.GetBoxValue(x - 1, y + 1, z - 1));
    }
    if (x + 1 < Grid.BoxGridArray.GetLength(0))
    {
    //back right
    NeighbourList.Add(Grid.GetBoxValue(x + 1, y, z - 1));
    //back right down
    if(y - 1 >= 0) NeighbourList.Add(Grid.GetBoxValue(x + 1, y - 1, z - 1));
    //back right up
    if(y + 1 < Grid.BoxGridArray.GetLength(1)) NeighbourList.Add(Grid.GetBoxValue(x + 1, y + 1, z - 1));
    }

    //back up
    if(y - 1 >= 0) NeighbourList.Add(Grid.GetBoxValue(x, y - 1, z - 1));
    //back down
    if(y + 1 < Grid.BoxGridArray.GetLength(1)) NeighbourList.Add(Grid.GetBoxValue(x, y + 1, z - 1));
    }

    if (z + 1 < Grid.BoxGridArray.GetLength(2))
    {
    //front
    NeighbourList.Add(Grid.GetBoxValue(x, y, z + 1));
    if (x - 1 >= 0)
    {
    //front left
    NeighbourList.Add(Grid.GetBoxValue(x - 1, y, z + 1));
    //front left down
    if(y - 1 >= 0) NeighbourList.Add(Grid.GetBoxValue(x - 1, y - 1, z + 1));
    //front left up
    if(y + 1 < Grid.BoxGridArray.GetLength(1)) NeighbourList.Add(Grid.GetBoxValue(x - 1, y + 1, z + 1));
    }
    if (x + 1 < Grid.BoxGridArray.GetLength(0))
    {
    //front right
    NeighbourList.Add(Grid.GetBoxValue(x + 1, y, z + 1));
    //front right down
    if(y - 1 >= 0) NeighbourList.Add(Grid.GetBoxValue(x + 1, y - 1, z + 1));
    //front right up
    if(y + 1 < Grid.BoxGridArray.GetLength(1)) NeighbourList.Add(Grid.GetBoxValue(x + 1, y + 1, z + 1));
    }

    //front up
    if(y - 1 >= 0) NeighbourList.Add(Grid.GetBoxValue(x, y - 1, z + 1));
    //front down
    if(y + 1 < Grid.BoxGridArray.GetLength(1)) NeighbourList.Add(Grid.GetBoxValue(x, y + 1, z + 1));
    }

    if (x - 1 >= 0)
    {
    //left
    NeighbourList.Add(Grid.GetBoxValue(x - 1, y, z));
    //left down
    if(y - 1 >= 0) NeighbourList.Add(Grid.GetBoxValue(x - 1, y - 1, z));
    //left up
    if(y + 1 < Grid.BoxGridArray.GetLength(1)) NeighbourList.Add(Grid.GetBoxValue(x - 1, y + 1, z));
    }
    if (x + 1 < Grid.BoxGridArray.GetLength(0))
    {
    //right
    NeighbourList.Add(Grid.GetBoxValue(x + 1, y, z));
    //right down
    if(y - 1 >= 0) NeighbourList.Add(Grid.GetBoxValue(x + 1, y - 1, z));
    //right up
    if(y + 1 < Grid.BoxGridArray.GetLength(1)) NeighbourList.Add(Grid.GetBoxValue(x + 1, y + 1, z));
    }

    //up
    if(y - 1 >= 0) NeighbourList.Add(Grid.GetBoxValue(x, y - 1, z));
    //down
    if(y + 1 < Grid.BoxGridArray.GetLength(1)) NeighbourList.Add(Grid.GetBoxValue(x, y + 1, z));
    return NeighbourList;
    }
    }

    public class BoxGridObject
    {
    public enum BoxType {
    Empty,
    num1,
    num2,
    num3,
    num4,
    num5,
    num6,
    num7,
    num8,
    num9,
    num10,
    num11,
    num12,
    num13,
    num14,
    num15,
    num16,
    num17,
    num18,
    num19,
    num20,
    num21,
    num22,
    num23,
    num24,
    num25,
    num26,
    Mined
    }
    public BoxType CellType;
    private BoxGrid<BoxGridObject> BoxGrid;
    private int x;
    private int y;
    private int z;

    public BoxGridObject(BoxGrid<BoxGridObject> BoxGrid, int x, int y, int z)
    {
    this.BoxGrid = BoxGrid;
    this.x = x;
    this.y = y;
    this.z = z;
    CellType = BoxType.Empty;
    }
    public void SetCellType(BoxType CellType)
    {
    this.CellType = CellType;
    }
    public BoxType GetCellType()
    {
    return CellType;
    }
    }

    public class TouchControl : MonoBehaviour
    {
    [SerializeField] private Camera Camera;
    [SerializeField] private Transform target;
    public Timer Tscript;
    public float distanceToTarget;
    private BoxGrid<BoxGridObject> Grid;
    private BoxGridObject BoxGridObject;
    private BoxInstantiate BoxInst;
    RaycastHit hit;
    private Vector3 previousPosition;
    private float startT = 0f, endT = 0f;
    void Update()
    {
    Ray ray = Camera.ScreenPointToRay(Input.mousePosition);
    if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonDown(1))
    {
    if(Physics.Raycast(ray, out hit))
    {
    if(hit.collider.gameObject)
    {
    startT = Time.time;
    }
    }
    }
    if (Input.GetMouseButtonUp(0))
    {
    if(hit.collider.gameObject.CompareTag("Box"))
    {
    Destroy(hit.collider.gameObject);
    BoxGridObject boxGridObject = Grid.GetBoxValue(hit.point);
    BoxInst.OpenBox(hit.point, boxGridObject);
    }
    }
    if(Input.GetMouseButton(2))
    {
    LoseGame();
    }
    if (Input.GetMouseButtonDown(1))
    {
    previousPosition = Camera.ScreenToViewportPoint(Input.mousePosition);
    }
    if (Input.GetMouseButtonUp(1))
    {
    endT = Time.time;
    if(endT - startT < 0.15f)
    {
    Destroy(hit.collider.gameObject);
    if(hit.collider.gameObject.CompareTag("Box"))
    {
    BoxInst.MarkBox(hit.point);
    }
    else if(hit.collider.gameObject.CompareTag("MarkedBox"))
    {
    BoxInst.UnmarkBox(hit.point);
    }
    }
    }
    if (Input.GetMouseButton(1))
    {
    Vector3 newPosition = Camera.ScreenToViewportPoint(Input.mousePosition);
    Vector3 direction = previousPosition - newPosition;

    float rotationAroundYAxis = -direction.x * 180;
    float rotationAroundXAxis = direction.y * 180;

    Camera.transform.position = target.position;

    Camera.transform.Rotate(new Vector3(1, 0, 0), rotationAroundXAxis);
    Camera.transform.Rotate(new Vector3(0, 1, 0), rotationAroundYAxis, Space.World);

    Camera.transform.Translate(new Vector3(0, 0, -distanceToTarget));

    previousPosition = newPosition;
    }
    if (distanceToTarget > 50f && Input.GetAxis("Mouse ScrollWheel") > 0f)
    {
    Camera.transform.position = Vector3.MoveTowards(Camera.transform.position, target.transform.position, 2000f * Time.deltaTime);
    distanceToTarget = distanceToTarget - 2000f * Time.deltaTime;
    }
    if (distanceToTarget < 10000f && Input.GetAxis("Mouse ScrollWheel") < 0f)
    {
    Camera.transform.position = Vector3.MoveTowards(Camera.transform.position, target.transform.position, -2000f * Time.deltaTime);
    distanceToTarget = distanceToTarget + 2000f * Time.deltaTime;
    }
    GameObject[] Numbers = GameObject.FindGameObjectsWithTag("Num");
    for(int i = 0; i < Numbers.Length; i++)
    {
    Numbers.transform.LookAt(Camera.transform);
    }
    }
    public GameObject UWON;
    public GameObject GameOver;
    public GameObject GridCenter;
    public GameObject Boom;
    public void WinGame()
    {
    if (((Tscript.CurrentTimeMin < PlayerPrefs.GetFloat("Mins")) || ((Tscript.CurrentTimeMin == PlayerPrefs.GetFloat("Mins")) && (Tscript.CurrentTimeSec < PlayerPrefs.GetFloat("Secs")))))
    {
    PlayerPrefs.SetInt("RecordNew", 1);
    PlayerPrefs.SetFloat("Mins", Tscript.CurrentTimeMin);
    PlayerPrefs.SetFloat("Secs", Tscript.CurrentTimeSec);
    }
    UWON.SetActive(true);
    GridCenter.SetActive(false);
    Time.timeScale = 0;
    RevealGame();
    }
    public void LoseGame()
    {
    GameOver.SetActive(true);
    GridCenter.SetActive(false);
    GameObject.Instantiate(Boom, new Vector3(0, 0, 0), Quaternion.identity);
    Time.timeScale = 0;
    RevealGame();
    }
    }

    public class BoxInstantiate : MonoBehaviour
    {
    public Object BoxPref;
    public Object MarkedBoxPref;
    public Object MineObject;
    public Object[] Nums;
    private BoxGridObject BoxGridObject;
    private BoxGrid<Vector3> Grid;
    private TouchControl TCscript;
    public void MarkBox(Vector3 HitPoint)
    {
    GameObject.Instantiate(MarkedBoxPref, Grid.GetBoxValue(HitPoint), Quaternion.Euler(-90, 0, 0));
    BoxGrid<int>.Mine--;
    }
    public void UnmarkBox(Vector3 HitPoint)
    {
    GameObject.Instantiate(BoxPref, Grid.GetBoxValue(HitPoint), Quaternion.Euler(-90, 0, 0));
    BoxGrid<int>.Mine++;
    }
    public void OpenBox(Vector3 HitPoint, BoxGridObject boxGridObject)
    {
    switch(boxGridObject.GetCellType())
    {
    case BoxGridObject.BoxType.Mined: TCscript.LoseGame(); GameObject.Instantiate(MineObject, Grid.GetBoxValue(HitPoint), Quaternion.identity); break;
    case BoxGridObject.BoxType.num1: GameObject.Instantiate(Nums[0], new Vector3(5, 5, 5) ,Quaternion.identity); break;
    }
    }
    }


    I tried calling a new class of 'BoxGridObject' and 'BoxInstantiate' in 'TouchControl' class but it didn't work, I really need to fix this error and understand roots of the problem.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
  3. IceCubeInk

    IceCubeInk

    Joined:
    Nov 25, 2022
    Posts:
    2
    I posted to understand which parameter in those actions is null and how I can fix this. I really don't understand, sorry for being such a newbie to scripting.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,742
    Sounds like perhaps you're skipping Step #2 of this process. You cannot skip that step. It's not optional.

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!


    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.


    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

    Finally, when you have errors, don't post here... just go fix your errors! Here's how:

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.