I’ve had several Null Reference Exception errors during the development of this project, and I felt like I had a handle on why they were happening, but this one has me stumped. I have a prefab (called specialFind) that gets instantiated several times throughout the scene on load. It has the following script on it (note that I took out several variables to save on space here, but if my comments aren’t clear, I can provide the full code):
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class SFdata : MonoBehaviour {
//public variables that receive data at instantiation
public int ID; //there are several others
CamMouseLook mouselook;
public GameObject viewer;
public Canvas viewerCanvas;
//Record Viewer Fields declared
private Text viewerID; //again, several others exist
void Start()
{
viewer = GameObject.Find("recordViewer");
viewerCanvas = viewer.GetComponent<Canvas>();
viewerCanvas.enabled = false;
Debug.Log("viewer is disabled");
mouselook = GameObject.Find("Main Camera").GetComponent<CamMouseLook>();
//assign correct components to record viewer fields
viewerID = viewer.transform.Find("Panel/Header").GetComponent<Text>();
//again, there are others
}
void OnMouseDown()
{
//when object is clicked on, open the dataViewer window and show the relevant data
mouselook.enabled = false;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
viewerCanvas.enabled = true;
Debug.Log("Viewer is enabled");
//set values for viewer
viewerID.text = "Special Find: " + ID.ToString();
//several others
}
public void closeRecordViewer()
{
SFdata SFdata = this;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
//next line throws Null Reference Exception
mouselook.enabled = true;
viewerCanvas.enabled = false;
}
}
So right now, things work as intended for the first two steps. If you click on an instance of specialFind it will open the data viewer and display the proper data. The problem happens when I click the ‘X’ button I made (grandchild of viewerCanvas), which has an OnClick event that calls closeRecordViewer(). For some reason, Start() and OnMouseDown() can use the variables like mouselook and viewerCanvas, but closeRecordViewer() gets a NRE when trying to access them. I thought that, being inside the same class, all methods would have access to these variables, but maybe I’m wrong? Can anyone tell me why this is happening?
Also, if you’ve got any criticism about the structure of the code, I’d very much appreciate that as well. But I mostly just want to get this thing working.