I have a class called Tile, which is composed of two integers and a boolean variable called isMine. In the following code, please focus your attention in the Debug.Log line and the if statement that follows.
using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using System.Collections;
using System;
public class buttonController : MonoBehaviour
{
private float buttonX;
private float buttonY;
private List<Tile> tileList;
private Button[] buttons;
public Canvas boardHolder;
public void OnTileClick()
{
buttonX = GetComponent<RectTransform>().localPosition.x / 30;
buttonY = GetComponent<RectTransform>().localPosition.y / 30;
buttons = GameObject.Find("Game Controller").GetComponent<gameController>().buttons;
tileList = GameObject.Find("Game Controller").GetComponent<gameController>().tileList;
Debug.Log("tileIsMine: " + tileList.Find(i => i.x == buttonX && i.y == buttonY).isMine);
if (tileList.Find(i => i.x == buttonX && i.y == buttonY).isMine)
{
GameObject.Find("Game Controller").GetComponent<gameController>().GameOver();
}
else
{
GameObject.Find("Game Controller").GetComponent<gameController>().TileClick(gameObject);
}
}
}
You see, whenever this is run, the Debug.Log line throws a NullReferenceException. Somehow, that tileList.Find is returning null.
Here’s everything I have tried to check:
-
Making sure buttonX and buttonY exist within tileList together.
-
Making sure there are items in tileList that have isMine set to true AND false. While I haven’t checked all of them, none of the times I ran the code did it not throw the exception, meaning it never found any of the trues and falses I found. It always returned null.
-
Making sure this script locates tileList, and building tileList previous to usage of this script.
-
Making a Tile and setting it to the tileList.Find code, and then using it.
By far the strangest thing is that this used to be working! It just suddenly stopped.
If you have any clue as to what may be causing this really strange behavior, please mention it to me. It could be anything I haven’t mentioned.
Cheers!