- Home /
random animations?
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!
Answer by japanitrat · Sep 11, 2011 at 11:01 PM
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: http://answers.unity3d.com/questions/8905/get-a-list-of-clips-in-an-animation-component-from.html
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
Your answer
Follow this Question
Related Questions
Select frame for Animation 1 Answer
how to stop animation loop? 1 Answer
Respawn script and door animation help 0 Answers