Scripting the ragdoll simulation

To be able to deactivate and activate the ragdoll simulation on the guards, we will use the following class. For simplicity, we will keep this class in theĀ UnityStandardAssets.Characters.ThirdPerson namespace.

This class will take care of enabling or disabling all the Rigidbodies of the guard GameObject children, avoiding touching the main Rigidbody that is still needed to keep the AI on the ground:

using UnityEngine; 
using System.Collections;

namespace UnityStandardAssets.Characters.ThirdPerson
{
public class RagdollCharacter : MonoBehaviour {

// At Start, deactivate all components that serve ragdoll
physics.
void Start() {
// Call DeactivateRagdoll method at start
DeactivateRagdoll();
}

// A method that activates all components for ragdoll physics
public void ActivateRagdoll() {

// Stop the AI by putting as alive = false the character
gameObject.GetComponent<AdvancedAI>
().SetAliveStatus(false);

// Disable Animator component
gameObject.GetComponent<Animator>().enabled = false;
// Disable NavMeshAgent component
gameObject.GetComponent<NavMeshAgent>().enabled = false;

// Find every Rigidbody in character's hierarchy
foreach (Rigidbody bone in
GetComponentsInChildren<Rigidbody>()) {
// Set bone's rigidbody component as not kinematic
bone.isKinematic = false;

//Enable collision detection for rigidbody component
bone.detectCollisions = true;
}

// this rigidbody must not detect collision and be
kinematic
GetComponent<Rigidbody>().isKinematic = true;
GetComponent<Rigidbody>().detectCollisions = false;

// Find every Collider in character's hierarchy
foreach (Collider col in
GetComponentsInChildren<Collider())
{
// Enable Collider
col.enabled = true;
}
// main collider must be disabled
GetComponent<CapsuleCollider>().enabled = false;
GetComponent<SphereCollider>().enabled = false;
}
}