With the transition between Idle and Jump configured in the Animator window, we can script a piece of code to trigger it. With the following recipe, we show how simple it is to control animations through scripting with Unity.
As usual, we follow on from the last recipe. You just need to add a C#
script in the Scripts
folder of the project (as you learned in Chapter 2, Importing 3D Graphics) and name it Char_Animator
.
Scripts
folder in your Project panel and double-click on the newly created script to open it in Monodevelop, the default Unity script editor.Animator
type variable to store the reference to the character animator and add the following line at the top of the script:private Animator charAnimator;
Start()
function; here we need to address the charAnimator
variable we created to the actual animator that we will attach to the character. We do that by adding the following line to the script:charAnimator=this.GetComponent<Animator>();
Jump
clip. In the Update()
function, add the following lines to intercept the pressing of the bar and set tJump
:if(Input.GetKey(KeyCode.Space)){ charAnimator.SetBool ("bJump", true); }
Refer to the following screenshot to check whether your code is correct:
Animator
controller to the character, but to do that, we first need to complete two steps:0
; it is strongly recommended!Packt_Animator
from the Animator
folder in the project panel in the Controller
field of the Animator component into the Inspector window, which should display None
in the Controller option field right now. Please refer to the following screenshot:Char_Animator
from the Scripts
folder onto the character in the scene. If you did things right, with the character selected, you should see both components displayed in the Inspector panel, as shown in the following screenshot:Once transitions are set up, code is required to trigger them so that the animation clips are played. The logic to follow is pretty straightforward; we cover it here.
The character needs an animator component to store an animator controller. The controller holds the clips, represented as states; the transitions between them; and a number of control parameters to manage the logic. The script contains the instructions that trigger the clips in the animator controller, thanks to the control parameters.
All this information may seem overwhelming at first, but with practice, you'll see it makes perfect sense and you'll get used to it!
18.223.170.63