How do I find other gameObject and disable it?
I've been searching everywhere and trying but I don't know what's getting me this error.
NullReferenceException: Object reference not set to an instance of an object Battery.BatteryLife () (at Assets/Scripts/Battery.cs:45) Battery.Update () (at Assets/Scripts/Battery.cs:22)
my BatteryLife() is below:
public GameObject flash;
Start () {
flash = GameObject.Find ("Flashlight");
}
Update () {
BatteryLife ();
}
void BatteryLife ()
{
if () {
} else {
flash.SetActive (false); //line 45
}
}
Am I not calling correctly?
Thanks for help in advance.
Answer by oStaiko · Oct 26, 2016 at 02:38 AM
Well the code you showed here is perfectly fine. The only issue it might be having is if there's no GameObject called "Flashlight" (Case Sensitive), or if it's a child of another GameObject. Personally I'd recommend using FindWithTag() over Find() just to be safe anyways. Unless the code is deleting that value somewhere else, the only issue is that it's not finding a GameObject.
For more help, check out the scripting API for GameObject.Find() and GameObject.FindWithTag()
Answer by Cynikal · Oct 26, 2016 at 02:41 AM
change:
if () {
to:
if (flash) {
//GameObject is found...
} else {
//GameObject is NOT found.
}
The null reference is saying it can NOT find the object you're trying to control...
Your answer
![](https://koobas.hobune.stream/wayback/20220612095435im_/https://answers.unity.com/themes/thub/images/avi.jpg)