- Home /
troubleshooting NullReferenceException
I'm getting a "nullreferenceexception" error from the following code:
void OnCollisionEnter()
{
GameObject landingPadLight = GameObject.Find ("landingPadLight");
print(landingPadLight.light.intensity);
}
the exact error is:
NullReferenceException givefuel.OnCollisionEnter () (at Assets/givefuel.cs:17)
the script is attached to an object that isn't hte light, but I want that object to turn the light on when it's collided with and so far I can't even access the intensity of it.
The name you use in GameObject.Find must be exactly the same string as the name you gave the object. For example "LandingPadLight" != "landingPadLight".
Answer by aaronov · May 24, 2013 at 03:01 AM
GameObject.Find() is likely not finding an object. You should be checking the return result before trying to access the object.
if (landingPadLight)
{
print(landingPadLight.light.intensity);
}
Answer by Ninita · May 24, 2013 at 07:45 AM
OnCollisionEnter never work with me. But the right assignature is void OnCollisionEnter (Collision Target), where the Target is your target of collision. Try assigning like that and if that din't work try with
void OnTriggerEnter(Collider objectCollider)
{
if(objectCollider.tag=="Player")
{
GameObject landingPadLight = GameObject.Find ("landingPadLight");
if(landingPadLight)
print(landingPadLight.light.intensity);
else
Debug.Log ("It didn't work");
}
}
if you use this you must have a collider (BoxCollider, CapsulCollider, etc) in your object, and there you must say that isTrigger activating that variable.
see http://www.youtube.com/watch?v=zsY86MdO_ZE&list=PL11F87EB39F84E292∈dex=12 or http://www.youtube.com/watch?v=kOLY_vrT7Ns&list=PL11F87EB39F84E292∈dex=25