does anyone know how to make a object, when hit by another object change to another prefab which is a ragdoll?
There’s a good Unity tutorial, FPS Tutorial, which gives very interesting hints about dead replacement - you should download and study this tutorial, it’s really great and teaches many interesting game tricks.
Anyway, replacing an object by a dead version (dead replacement) depends on what the object is. The replacement of simple objects is easy: just instantiate the new object at the same position and with the same rotation, then delete the old one. If the object is a rigidbody, do it in OnCollisionEnter; if it’s a CharacterController, use OnControllerColliderHit:
var replacement: Transform;
function OnControllerColliderHit(hit: ControllerColliderHit){
if (hit.gameObject.CompareTag("SomeTag")){ // if collided with the right object...
// create replacement at same position and with same rotation:
var dead: Transform = Instantiate(replacement, transform.position, transform.rotation);
// destroy the original object:
Destroy(gameObject);
}
}
For objects that may have moving children, however, things are more complicated: after instantiating the ragdoll, you must copy position and rotation of each child. This is typically the case of animated characters: its ragdoll must have the same bones, with rigidbodies attached to some of them. In order to copy the children position/rotation, a recursive function is necessary:
var replacement: Transform;
function OnControllerColliderHit(hit: ControllerColliderHit){
if (hit.gameObject.CompareTag("SomeTag")){ // if collided with the right object...
// create replacement at same position and with same rotation:
var dead: Transform = Instantiate(replacement, transform.position, transform.rotation);
// copy position and rotation to the children recursively:
CopyTransformsRecurse(transform, dead);
// destroy the original object:
Destroy(gameObject);
}
}
static function CopyTransformsRecurse (src: Transform, dst: Transform) {
dst.position = src.position;
dst.rotation = src.rotation;
dst.gameObject.active = src.gameObject.active;
for (var child: Transform in dst) {
// match the transform with the same name
var curSrc = src.Find(child.name);
if (curSrc) CopyTransformsRecurse(curSrc, child);
}
}
See more info in the amazing FPS Tutorial.