- Home /
Variable Assigning with GameObject.Find("") causing NullReferenceException?
buttons = new Button[6];
interactUI = GameObject.Find("Interact");
player = GameObject.Find("Player");
title = GameObject.Find("IntText").GetComponent<Text>();
ml = GameObject.Find("Main Camera").GetComponent<MouseLook>();
for (int i = 0; i <= 5; i++)
{
buttons[i] = GameObject.Find("IntBtn" + i).GetComponent<Button>();
Debug.Log(buttons[i]);
}
corners = new Vector3[4];
buttons[0].onClick.AddListener(event0);
buttons[1].onClick.AddListener(event1);
buttons[2].onClick.AddListener(event2);
buttons[3].onClick.AddListener(event3);
buttons[4].onClick.AddListener(event4);
buttons[5].onClick.AddListener(event5);
interactUI.SetActive(false);
So this is what is inside my Awake() function. When this prefab instantiates, it assigns all of these variables to a gameobject found in the hierarchy. What is very strange is how this script works perfectly for a hierarchy object that it is attached to but not for any of the prefabs which are instantiated. For the prefabs I am getting a bunch of nullreference exceptions from both this and later on when the variables are referenced again, but only for when this script is attached to prefabs. Why is this happening and how do I fix it?
Are you sure the objects you find are enabled when the Find
method is called? If you're disabling the objects at runtime, having the NullReference for the prefabs only does not surprise me.
As shown in the question, I find the interactUI (parent gameObject containing UI elements) and all the UI elements inside it (title, buttons, etc) before disabling the gameobject
Yes, this script disables the interactUI
gameObject, but isn't there any other object disabling it (or one of its parents) before this script can run?
If you instantiate multiple times this object, then, the 1st object will run without any problem, but the other instances won't find the interactUI
gameObject.