- Home /
Play either the first or second animation on an object without specifying its name
I have multiple gameobjects throughout the scene that have two animations. I need to play either the first or second animation without changing their imported animation names.
Is there a way I can include in the function for it to call the animation using its element? Like element 0, element 1, as found in the inspector.
Bare with me, I do modeling/texturing/animation. Some scripting makes sense then I run into something I can't figure out like this. Thanks for any help!
Currently I have:
#pragma strict
function OnMouseOver()
{
if(Input.GetMouseButtonDown(0))
{
animation.Play("r_gear_down");
}
}
This works just fine, however I would have to write over 500 individual scripts for each separate game object. I'd like to write one script and add it to each one instead. I monkeyed around with trying to identify animation clips with no success.
Thanks! (I used the format code button, but it appears it didn't want to give the lines. Sorry!)
Answer by thomasindustry · Apr 08, 2014 at 10:16 PM
My javascrtipt is super rusty, if you get a list of all the names of the AnimationStates, you should be able to play them by element.
var animNames = new Array();
var currAnim: int = 0;
var theAnimation: Animation;
function Start () {
theAnimation = gameObject.GetComponent(Animation);
var animationCount: int = 0;
for(state in theAnimation)
{
var nextState : AnimationState;
nextState = state;
animNames[animationCount] = nextState.name;
animationCount++;
}
}
function OnMouseOver()
{
if(Input.GetMouseButtonDown(0))
{
currAnim = (currAnim + 1) % animNames.length;
theAnimation.Play(animNames[currAnim], PlayMode.StopAll);
}
}
Perfect! Exactly what I needed. I was able to add a bit to get it to play between elements 1-2 and 3-4 depending on what state some other gameobject animations are in. Thanks!! (Alas I am new so I am unable to give it a thumbs up, something about 15 rep... but thumbs up!)
Your answer
Follow this Question
Related Questions
How would I go about carrying out another object's animation IN C#! 1 Answer
Animations Not Working 2 Answers
How to loop unity?JS 3 Answers
Animation doesn't work 1 Answer
Play simple animations on demand 1 Answer