In case you haven't included a sufficient number of props to your character when modeling and animating it, you might want to give her the chance of collecting new ones at runtime. In this recipe, we will learn how to instantiate a GameObject and assign it to a character, respecting the animation hierarchy.
For this recipe, we have prepared a Unity Package named Props
, containing a basic scene that features an animated character and a prefab named badge. The package can be found inside the 1362_07_06
folder.
To add a rigid prop at runtime to an animated character, follow these steps:
Props
Unity Package. Then, from the Project view, open the mecanimPlayground level.-0.08
, Y: 0,
Z: 0.15
; and Rotation to X: 0.29
, Y: 0.14
, Z:-13.29
.0
, Y: 0.5
, Z: 2
.AddProp.cs
.using UnityEngine; using System.Collections; public class AddProp : MonoBehaviour { public GameObject prop; public Transform targetBone; public Vector3 positionOffset; public Vector3 rotationOffset; public bool destroyTrigger = true; void OnTriggerEnter ( Collider collision ){ if (targetBone.IsChildOf(collision.transform)){ bool checkProp = false; foreach(Transform child in targetBone){ if (child.name == prop.name) checkProp = true; } if(!checkProp){ GameObject newprop; newprop = Instantiate(prop, targetBone.position, targetBone.rotation) as GameObject; newprop.name = prop.name; newprop.transform.parent = targetBone; newprop.transform.localPosition += positionOffset; newprop.transform.localEulerAngles += rotationOffset; if(destroyTrigger) Destroy(gameObject); } } } }
-0.08
, Y: 0,
Z: 0.15
; Rotation Offset: X: 0.29
, Y: 0.14
, Z:-13.29
).Once it's been triggered by the character, the script attached to PropTrigger instantiates the assigned prefab, making it a child of the bones that they have been "placed into". The Position Offset and Rotation Offset can be used to fine-tune the exact position of the prop (relative to its parent transform). As the props become parented by the bones of the animated character, they will follow and respect its hierarchy and animation. Note that the script checks for the preexisting props of the same name before actually instantiating a new one.
3.16.137.38