0
\$\begingroup\$

I haven't worked with the animation system in Unity before and am getting overwhelmed trying to figure out how to start playback of a simple animation. Yes, this is a "stupid question", but I've spent more than an hour researching this and can't find an answer on how to do something this simple:

I've created an animation called CameraZoom for the scene's camera. The CameraZoom animation is supposed to play when a specific event occurs, so I want to trigger it from script. I've created the animation on the camera, it has the Animator component attached to it, and by default the animation plays as soon as the scene starts. I can stop the animation from code, but when I try to start it, nothing happens. Here's my code:

private Animator myAnimation;
void Start () {
    myAnimation = gameObject.GetComponent<Animator>();
    myAnimation.Stop();
}
public void ZoomOut() {
    Debug.Log("Zoom out!");
    myAnimation.Play("CameraZoom");
}

This script successfully stops the animation when the scene starts, but when I call ZoomOut, the animation doesn't play. enter image description here

Here are the states:

It may be I'm not understanding how to utilize the state machine and I'm trying to play the animation incorrectly. Tutorials I can find on the Animator are either too vague or discuss other features such as triggers and parameters that I don't know how to apply to such a simple task.

I know I could whip up a Coroutine to zoom the camera out in about 30 seconds, but I'm trying to learn how to utilize the Animator for basic keyframe animations.

\$\endgroup\$
1
\$\begingroup\$

You don't need to stop the animation if you have an empty animator state as the starting point.

From there you have two options. You can create parameters that triggers the transition to your CameraZoom state, which you can activate by

getComponent<Animator>().SetTrigger("CameraZoomTrigger");

Or you can specifically order the animator to jump to a defined state. (docs)

getComponent<Animator>().CrossFade("CameraZoom", 0); 

There's also the work in progress Playables API which lets you dynamically load an animation clip into an animator. You can look into that if you're feeling adventurous.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.