Hi,I upon creating pause/console button of sorts in c#,I used get component to disable & enable mouse look (both vertical[in main camera] & horizontal[in fps controller]). This worked fine for couple of days, but after downloading free asset from asset store(had 1 JS script) now my own script gives me a null reference on those lines(inside update).
if(CheatMenuOpen==true)
{
fpsContrl.GetComponent<MouseLook>().enabled=false;
mcamera.GetComponent<MouseLook>().enabled=false;
}
else
{
fpsContrl.GetComponent<MouseLook>().enabled=true;
mcamera.GetComponent<MouseLook>().enabled=true;
}
fpsContrl & mcamera are public. I have battled with this null reference exception whole morning and I just dont know how to fix it. Any help is appreciated, thanks in advance
GetComponent needs a type to be specified. Presuming the components are already being referenced in the script, and fpsContrl is of type “FirstPersonController” and mcamera being a “Camera” type:
if (CheatMenuOpen == true) {
if (fpsContrl!= null) fpsContrl.enabled = false;
if (mcamera != null) mcamera.enabled = false;
} else {
if (fpsContrl!= null) fpsContrl.enabled = true;
if (mcamera != null) mcamera.enabled = true;
}
If you want to get a component from a GameObject:
fpsContrl = (FirstPersonController) someGameObject.GetComponent<FirstPersonController>();
mcamera = (Camera) someGameObject.GetComponent<Camera>();
http://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
If you’re getting a null reference in that block of code, then one of the following must be true:
- fpsContrl is null (not initialized or not set in the inspector)
- mcamera is null (not initialized or not set in the inspector)
- fpsContrl doesn’t have a MouseLook component
- mcamera doesn’t have a MouseLook component
I’d add some Debug.Log lines to figure out which thing is null. Perhaps something like:
Debug.Log(fpsContrl);
Debug.Log(mcamera);
Debug.Log(fpsContrl.GetComponent<MouseLook>());
Debug.Log(mcamera.GetComponent<MouseLook>());