Hello, I was wondering if anybody knows of a way to make random animations play.

I would like it so on the input of (“fire1”) 3 different animations have the option of playing at random.

This is what I have so far:

if (Input.GetButtonDown ("Fire1"))
  animation.CrossFade("attack2");
else
  animation.CrossFade("attack1");

}

It doesn’t work, it weights a few seconds then plays the attack1 animation.

If anyone knows of a solution that would be great!

You should be aware that Input.GetButtonDown returns true only in the frame the user started to press the button down, see the reference. So what happens is that “attack1” is started immediatly after the frame where the user pressed the button.

What you want to do is to pick one of the available animation clips and play this one when the user presses the button. Here is a javascript example on how to obtain all clips for a gameobject: Get a list of clips in an animation component from script. - Questions & Answers - Unity Discussions

you can use that function now like this:

if(Input.GetButtonDown("Fire1"))
{
    var names = GetAnimationNames(this.animation);
    var randomIndex = Math.floor(names.length * Math.random()); 
    this.animation.CrossFade(names[randomIndex]);
}

It’s as easy as that (although not good performance-wise). Math.random() returns a number between 0 and 1 which we will multiply with the amount of animation names available, thus randomIndex now contains a natural number between 0 and the amount of available names (3 in your case). Note the use of Math.floor() which removes any fractions of its arguments, so 1.5313 becomes 1. Apply this as index to the names list and you get a random animation name which you can use for Animation.Crossfade