Recursive Rigidbody Method

,Hi guys. Wrote a method which find highest gameObject parent with Rigidbody.

public Rigidbody RecursiveReturnRigidbodyParent(GameObject gameObjectGrabed)
{
    while (gameObjectGrabed.GetComponentInParent<Rigidbody>())
    {
        gameObjectGrabed = gameObjectGrabed.transform.parent.gameObject;
    }
    return gameObjectGrabed.GetComponent<Rigidbody>();
}

Aaand thats the problem:

NullReferenceException: Object reference not set to an instance of an object

Im grabbing object using raycast. If the object contains rigidbody then it search further if any of the parent object have rigidbody.

Because you are getting a GameObject that might have no rigidbody and you are returning that.

public Rigidbody RecursiveReturnRigidbodyParent(GameObject gameObjectGrabed)
{
	// Ensure the current object has a rigidBody
	if(gameObjectGrabed.GetComponentInParent<Rigidbody>() == null)
		return null;
	
	var currObject = gameObjectGrabed.GetComponentInParent<Rigidbody>() ;
	
	while (gameObjectGrabed.GetComponentInParent<Rigidbody>() != null)
    {	
		currObject = gameObjectGrabed.GetComponentInParent<Rigidbody>();
		gameObjectGrabed = gameObjectGrabed.transform.parent.gameObject;
    }
    return currObject;
}