Pablo Darde
Pablo Darde

Reputation: 6402

Play/Stop animation/animator on instantiated object

I'm developing a unity game and basically, I have a prefab with a sprite inside it. I created an animation attached to that sprite.

FrogPrefab
    |__ FrogSprite

I created a script with a public field "prefab" where I pass my prefab.

My question is, how can I stop and play this animation from my script.

I instantiated my prefab from my start method...

public GameObject gameCharacterPrefab;

private GameObject frog;

void start() {
    frog = (GameObject)Instantiate(gameCharacterPrefab, objectPoolPosition, Quaternion.identity);
}

I'm trying to do something like that...

frog.animation.stop();

appreciate any help

Upvotes: 2

Views: 20994

Answers (2)

Codemaker2015
Codemaker2015

Reputation: 1

For playing animation we can use Play() but for stopping the animation the Stop method is become obsolete in Unity 2019 or higher versions. So, For disable animation we can use enable flag and set it to false.

//For playing the animation
frog.GetComponent<Animator>().Play(); 
or
frog.GetComponent<Animator>().enable = true; 

//For stop the animation
frog.GetComponent<Animator>().enabled = false;

Upvotes: 1

Programmer
Programmer

Reputation: 125275

First, note that the function should be called Start not start. Maybe this is a typo in the question but it's worth mentioning.

Use GetComponent to get the Animator or Animation component. If the animation is a child of the prefab then use GetComponentInChildren.

If using the Animator component:

public GameObject gameCharacterPrefab;
private GameObject frog;
Vector3 objectPoolPosition = Vector3.zero;
Animator anim;

Instantiate the prefab

frog = (GameObject)Instantiate(gameCharacterPrefab, objectPoolPosition, Quaternion.identity);

Get the Animator component

anim = frog.GetComponent<Animator>();

Play animation state

anim.Play("AnimStateName");

Stop animation

anim.StopPlayback();


If using the Animation component:

public GameObject gameCharacterPrefab;
private GameObject frog;
Vector3 objectPoolPosition = Vector3.zero;
Animation anim;

Instantiate the prefab

frog = (GameObject)Instantiate(gameCharacterPrefab, objectPoolPosition, Quaternion.identity);

Get the Animation component

anim = frog.GetComponent<Animation>();

Play animation name

anim.Play("AnimName");

Stop animation

anim.Stop();

Upvotes: 3

Related Questions