In case you haven't included a sufficient number of props for your character when modeling and animating it, you might want to give him the chance to collect new ones at runtime. In this recipe, we will learn how to instantiate a game object and assign it to a character, respecting the animation hierarchy.
For this recipe, we have prepared a project named MixamoProject
, containing several assets such as levels, animated characters, and props. You can find it inside the 0423_05_codes
folder.
To add a rigid prop to an animated character at runtime, perform the following steps:
AddProp.cs
.using UnityEngine; using System.Collections; public class AddProp : MonoBehaviour { public GameObject prop; public string propName; public Transform targetBone; public Vector3 propOffset; public bool destroyTrigger = true; void OnTriggerEnter ( Collider collision){ if (targetBone.IsChildOf(collision.transform)){ bool checkProp = false; foreach(Transform child in targetBone){ if (child.name == propName) checkProp = true; } if(!checkProp){ GameObject newprop; newprop = Instantiate(prop, targetBone.position, targetBone.rotation) as GameObject; newprop.name = propName; newprop.transform.parent = targetBone; newprop.transform.localPosition += propOffset; if(destroyTrigger) Destroy(gameObject); } } } }
-0.05
, -0.15
, and -0.06
respectively. Finally, deselect the Destroy Trigger checkbox.Badge
; Prop Name: Badge
; Target Bone: swat:Spine2
; Prop Offset: X: -0.11
, Y: 0.05
, Z: 0.11
. Also, deselect the Destroy Trigger checkbox.Once it's been triggered by the character, the script attached to the spheres instantiates the assigned Prefabs, making them children of the bones they have been placed into. The Prop Offset field 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 pre-existing props of the same name before actually instantiating new ones.
18.218.171.212