- Home /
Script decides not to run anymore
I'm a minute from absolutely raging on my computer. I have a script that applies a "buoyancy force" to an object in water (in my case a trigger box). It was working just fine until the other day where out of no where Unity is telling me that floatingRigidbody.AddForce(force) isn't set to an instance of an object. Which makes no sense, because the variable floatingRigidbody is a public GameObject which gets assigned when an object enters a trigger.
public GameObject floatingRigidbody;
void OnTriggerStay(Collider other) {
if(other.gameObject.GetComponent<Rigidbody>() && other.gameObject.tag != "Player") {
isUnderWater = true;
floatingRigidbody = other.gameObject;
clampPercentage();
}
}
This code ran fine before. Now the whole NullReferenceException error is keeping the script from running. I don't know why this is happening and it seems to happen often. and YES I have done the whole if(floatingRigidbody != null) thing, and that doesn't work either. Is there a hero out there that can save my computer from complete destruction?
Answer by iwaldrop · Jan 17, 2013 at 03:01 AM
I really don't see anything that jumps out as being wrong with the code above, but a couple things spring to mind that might help Unity dry it's eyes.
Try this:
public GameObject floatingRigidbody;
void OnTriggerStay(Collider other)
{
if (other.GetComponent<Rigidbody>() is Rigidbody && other.tag != "Player")
{
isUnderWater = true;
floatingRigidbody = other.gameObject;
clampPercentage();
}
}
The only thing I really added there was a check to make sure that a Rigidbody is indeed attached. This shouldn't affect this code working though. But it will affect how the other code runs, because if you assign a GameObject to floatingRigidbody that doesn't have a Rigidbody then your other code will barf. Better to be safe than sorry either way.
Your answer
Follow this Question
Related Questions
object not set to instance? 1 Answer
"Object reference not set to an instance of an object" error 1 Answer
Unity3D 4.2.0 Crasing ... 0 Answers
Object reference not set to... 1 Answer