The goal of this lab is to insert a character into a scene that displays animation that changes based on context. This introduces the Animator component and the associated Animator Controller state machine.
AnimationClip
to see how many animation clips you have). If you don't have a character and animations, you can retrieve a bunch by importing the “Characters” package from the Assets menu, or the “Raw Mocap data for Mecanim” package from the asset store. FPSController
game object and add a character that is ready for animation, such as Ethan
(from the Characters package) or DefaultAvatar
(from the Mocap package). Set the scene up so that the characer is facing you some distance away.Animator
component, add it.Animation
. In that folder, right-click and select Create→Animation Controller. Take this new controller and drag it into the Controller
slot of the Animator
component of your character.UserPresent
. Then back in the Conditions sub-panel of the transition from the first to the second animation, you should now select this parameter. Collision Sphere
to it, make it a Trigger
and adjust its radius so that it will trigger at a distance about half the way between you (the first person controller) and the character. Add a new scrip to the character that intercepts the trigger event (void OnTriggerEnter(Collider col)
) and set the UserPresent trigger parameter in the animator controller. You do that by first acquiring a reference to the Animator
component (hint: Use GetComponent
). Then on that component you call SetTrigger(“UserPresent”)
. Check out the documentation for ''SetTrigger''. If everything is working properly, you should now see the transition from the first to second animation when you walk towards the character. Make sure that the second animation only plays once and then returns to the first animation (until you cross the trigger boundary again). Animator
component every time you want to access its SetTrigger
method is not fast. Also, it is not particularly fast to set the trigger by name, i.e. the state machine has to search for the matching string for that parameter before setting its value. Instead you can pre-calcualte the hash ID for this parameter and pass that id into the function. So, to optimise do two things: Store a reference to the animator component AND a hash id value for the parameter you want to change as member variables in your behavior script. Only assign values to these two variables once.