- Home /
How to go to starting point of an animation which is running already?
Hi. I am kind of a beginner to Unity.
So. an animation(which is a prefab.) is playing in my run time. I want to include a script to this prefab which makes my animation play from starting point on some condition.
Help me in solving this. Or correct me if I had misunderstood things wrongly.
Thanks in advance. :)
Answer by Tomer-Barkan · Apr 15, 2015 at 02:22 PM
The animator component has a Play() method that accepts an animation state and also a point in time of the animation in which you want to start from:
You can use this code from a script attached to the same object as the animator:
string startAnimationState = "StartState";
Animator animator = gameObject.GetComponent<Animator>();
animator.Play(startAnimationState, -1, 0);
Assuming the state you want to restart playing is called "StartState" in the animation controller, and that you only have one layer.
Hey. Thanks for replying :) Your code works. But there is a problem. I have multiple game objects instantiated to which this code is to be added.
When the condition gets satisfied, only the first game object gets restarted. That is the first animation which gets instantiated as game object during the run time.
Please help me in solving this. Thanks again for replying. :)
And you attached my script too all these objects? Share your entire code, it's hard to figure out what's going on without it.
Yes. I attached this script of yours to all the prefab(3 different prefabs actually) I want to make that function.
Now, during the run time the same script would be automatically attached to the instantiated game objects.
Here is my code snippet
void Update() { if(condtion is true){ string startAnimationState = "StartState";
Animator animator = gameObject.GetComponent();
animator.Play(startAnimationState, -1, 0); } }
And these animators each have separate starting states named StartState.
Thanks in advance! Cheers :)
As long as they're all enabled, all have an animator with a state called StartState, and the condition is true for all of them, I see no reason why it shouldn't work. Look deeper and try to find what you did wrong.
The code you posted is just fine. There is a bug somewhere in your other code, you'll have to do some debugging to find it, we can't debug it for you. You can use a debugger or Debug.Log to print the condition values just before the if, see if the code gets executed at all and if not try to figure out why.