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?

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.