Devsignerz
Devsignerz

Reputation: 13

Unity doesn't play animation with C#

So, the animation plays on "Play automatically" but when I can't play it from my C#. here's the code running it:

[SerializeField]
private GameObject theThing;

theThing.gameObject.GetComponent<Animation>().Play();
//i also tried using Animator but no luck

i also have the Legacy turned on in the anim file

Upvotes: 0

Views: 836

Answers (2)

Devsignerz
Devsignerz

Reputation: 13

So, my problem was that i set the prefab to play the animation instead of the instantiated one. I also used Animator again like this:

theThingIns.gameObject.GetComponent<Animator>().Play();

Upvotes: 0

Hristo
Hristo

Reputation: 1815

If you are going to use Legacy for the animations, you must set the speed of each state in the animation. The following code should do the job:

private GameObject theThing;
public void PlayAnim()
{
    foreach (AnimationState state in theThing.GetComponent<Animation>())
    {
        state.speed = 0.5f;
    }
    this.GetComponent<Animation>().Play();
}

Upvotes: 1

Related Questions