- Home /
The question is answered, right answer was accepted
NullReferenceExeption on gameObject.SetActive
Alright, again I have to seek rescue from the forum... So, this time I'm trying to set UI objects (buttons, dropdowns) visible/invisible, but I keep getting the NullReferenceExeption error. Got no idea why this would be, anybody do? Here's my code:
public class RestartScript : MonoBehaviour {
public MeshCreator meshCreator;
void Start () {
gameObject.SetActive (false);
}
void Update () {
if (meshCreator.roundStarted) {
gameObject.SetActive (true);
}
}
public void Restart () {
int scene = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(scene, LoadSceneMode.Single);
}
}
I have put in the reference in the inspector, but it doesn't seem to be working.
Also, the error comes from line 13, where it says
if (meshCreator.roundStarted) {
gameObject.SetActive (true);
}
You don't have included your whole script so the line numbers are off. What exact line does the error come from?
ps: your logic seems to be flawed here. You deactivate the gameobject in Start which will completely turn off this gameobject. That means no Update callback will be executed anymore. The script can never activate itself if it's not already active. This makes no sense.
If you get a NullReference exception, please include the whole stacktrace and the exact line.
Bunny083 has mentioned it already and it is correct. There is no reference because this script will never run. Start will turn it iff then Update will never run. What you need to do is create a second script and GameObject that will manage this script and turn it on and off outside of it. A manager script to handle all of the stuff like this in the level. A Game$$anonymous$$anager is very common for stuff like this and is highly recommended.
Answer by shadowpuppet · Apr 16, 2018 at 09:22 PM
I tried this simple script below and it didn't work because once I set the gameObject to false, the script stops running. I didn't get any errors though, it just didn't work. The script is on the gameObject you are setting to false just as you have it
void Update(){
if (Input.GetKeyDown (KeyCode.A)) {
gameObject.SetActive (false);
Debug.Log ("off");
}
if (Input.GetKeyDown (KeyCode.D)) {
gameObject.SetActive (true);
Debug.Log ("on");
}
}
}
So basically I need to control the true/false mechanism from outside the ones that need to be set? That does make a lot of sense though.
No, what doesn't make a lot of sense is trying to run a script on a gameObject that is, in effect, non existent from the Start. you can pretty much use the same script but make the the gameObject you want to make false public, and put the script somewhere else
Alright, thanks. $$anonymous$$anaged to make it work now :D A silly mistake that was.