I have an String array which contains a names of animation clips like sample_5.anim and my animations are in the assets folder. How can I play them by sequence with transitions from a C# script. Thank you for your help.
You have to find a way to listen to the end of a clip to play the next one. I would suggest storing of the current playing clip and use Animation.IsPlaying to know when it’s done playing.
Example script :
using UnityEngine;
using System.Collections;
using System;
public class AnimationSequencePlayer : MonoBehaviour {
public Animation animation; // The animation we want to play the clips in.
public AnimationClip[] animationClips; // The animation clips we want to play in order.
int _currentClipOffset;
void Start() {
foreach (AnimationClip clip in animationClips) {
animation.AddClip(clip, clip.name); // Make sure the animation player contains all of our clips.
}
}
public void PlaySequence() {
_currentClipOffset = 0; // Reset the index to start at the beginning.
PlayNextClip();
}
public void StopSequence() {
animation.Stop();
StopAllCoroutines();
}
void PlayNextClip() {
animation.Play(animationClips[_currentClipOffset].name); // Play the wanted clip
if (_currentClipOffset != animationClips.Length) { // Check if it's the last animation or not.
StartCoroutine(WaitForAnimationEnd(() => PlayNextClip())); // Listen for end of the animation to call this function again.
_currentClipOffset++; // Increase index for next time;
}
}
IEnumerator WaitForAnimationEnd(Action onFinish) {
while (animation.isPlaying) { // Check if the animation is playing or not
yield return null;
}
if (onFinish != null) {onFinish();} // Call the function give in parameter.
}
}
I would suggest you to keep your clips in Resources folder. e.g., Assets/Resources/AnimFrames
. Later use:
Resources.Load<T>()
to retrieve all the clip from above specified path. Then you can use co-routine to schedule them one after another OR Invoke a function after some delay for each clip.