How to play random animation clip?

I experimented with Animator and Animation component.

So what I want is, if character now need to do [Attack] action, I want to play random one of ‘Attacking’ motions from many.

I tried with Animation component and failed with many googling found few approach.

How should I do?

Thanks.

C# :

public Animation[] attacks; //Put attack animations here

void Start () {
   Random.seed = System.DateTime.Now.Ticks; //Just for full randomization
}

void Attack () {
   Animation.Play(attacks[Random.Range(0,Mathf.RoundToInt(attacks.Length));
}

US:

var attacks : Animation[]; //Put attack animations here

function Start () {
   Random.seed = System.DateTime.Now.Ticks; //Just for full randomization
}

function Attack () {
   Animation.Play(attacks[Random.Range(0,Mathf.RoundToInt(attacks.Length));
}

I don’t have time to test these codes, but if any error occur, please write a comment about it

Thx for reply,

But, what do you mean Animation.Play?

Declare varible like,

public Animation animate;
public Animation[] animateClips;
and,
          animate = GetComponent<Animation>();
and then,       
          animate.Play(animateClips[Random.Range(0, Mathf.RoundToInt(animateClips.Length))]);

then I got this error,

Assets/Script/EnemyAnimControl.cs(52,17): error CS1502: The best overloaded method match for `UnityEngine.Animation.Play(UnityEngine.PlayMode)’ has some invalid arguments

you need to declare an ANIMATOR from which you are playing your animation, something like this:

public Animator _animator;
public Animation[ ] animateClips;

and then you play it:

_animator.Play…blah blah blah

basically, you play your aniMATIONS from your aniMATOR. Hope that helps

Well now that’s not entirely true since you can indeed also play aniMATIONS from your aniMATION component :slight_smile:

@vintar
anyWAY :smile: that’s how I do it, just tried to help a fella… don’t be so judgMENTAL :stuck_out_tongue:

Animation is legacy
Animator is mecanim and more relevant (unless OP was using legacy)

public Animation animate;
public AnimationClip[] animateclips;
and,
          animate = GetComponent<Animation>();
and then,    
          animate.Play(animateclips[Random.Range(0, Mathf.RoundToInt(animateclips.Length))].name);

because animation.play(String name) use string parameter

this is old way of doing it. the legacy system ( wich IMHO was much easier to control through scripts than the animator system… )

any way of doing this with animator, transitions, states and all this obfuscated things ?