NPC gets up inside terrain (disconsidering the terrain collider)

In my game humanoid NPCs have a lot of physics interaction, specially when the player casts spells with explosions or turning of the enemy’s gravity. All these interactions trigger a ragdoll in the game object (by a specific set of scripts that you can see here: From animation to ragdoll and back - Questions & Answers - Unity Discussions).

When they fall back to the ground, one of these ragdoll system’s scripts sends a Raycast to detect where they are to blend the actual position to start a getting up animation.

What is going wrong is that the moment they start to get up, their root changes to a y = 0, and the getting up animation occurs at this height (not on the top of the terrain mesh, or on the top of a building), and they stay there, only getting back to terrain level afterwards, because of the NavMeshAgent.

Here is the part of the code I’m using that resets the NPCs root position, so the animation occurs exactly where their body is (it can be very far away, as a consequence of an explosion, for example):

//Now cast a ray from the computed position downwards and find the highest hit that does not belong to the character 
				RaycastHit[] hits=Physics.RaycastAll(new Ray(newRootPosition,Vector3.down)); 
				foreach(RaycastHit hit in hits)
					if (!hit.transform.IsChildOf(transform))
						newRootPosition.y=Mathf.Max(newRootPosition.y, hit.point.y);


Any help would be appreciated…

The problem was that the Raycast didn’t always hit the terrain collider, so many times the NPC’s “Getting up” animation would occur at y=0.

So I took the ragdolled state verification out of the Update () and established it as a variable (I still don’t know why this worked, but it was a good guess) and I rippled of the comparison between the RaycastHit and the newRootPosition.y.

Now it is working!

No more underground animations!