Game Development Reference
In-Depth Information
Accessing controllers from a script
Like most things in Unity, to access another component, we just need a reference to it.
With the animation controllers, it is no different.
Update your CharacterMovement.cs script by performing the following steps:
• A new Animator reference to hold a link to our sprites animator is needed, as
mentioned in the following code:
//Reference to the player's animator component.
private Animator anim;
• Discover the actual animator from the sprite object within the Awake function to
ensure we capture it at startup using the following code:
void Awake()
{
//Setting up references.
playerRigidBody2D =
(Rigidbody2D)GetComponent(typeof(Rigidbody2D));
playerSprite =
transform.Find("PlayerSprite").gameObject;
anim =
(Animator)playerSprite.GetComponent(typeof(Animator));
}
• In the Update function, we update a float parameter we defined earlier in the
animator with the value of the movement that we got from the user control. Refer
to the following code:
void Update(){
//Cache the horizontal input.
movePlayerVector = Input.GetAxis("Horizontal");
anim.SetFloat("speed", Mathf.Abs(movePlayerVector));
Now if you run the project, your hero will start running in the correct direction when you
tell him to and then rest when you stop.
Search WWH ::




Custom Search