Owen D.
Owen D.

Reputation: 425

Get name of current animation state

How can I get the name of the current state in a layer on my Animator component? I realize that I can compare the name with GetCurrentAnimatorStateInfo(0).IsName("statename") but I don't want to have to run that for each state in my layer. Is it possible to simply get the name of the current state?

Upvotes: 11

Views: 30416

Answers (4)

Digvijaysinh Gohil
Digvijaysinh Gohil

Reputation: 1455

We can get the current playing clip name in the layer using following code

private Animator animator = GetComponent<Animator>();
private AnimatorClipInfo[] clipInfo;

public string GetCurrentClipName(){
    int layerIndex = 0;
    clipInfo = animator.GetCurrentAnimatorClipInfo(layerIndex); 
    return clipInfo[0].clip.name;
}

Upvotes: 12

Angel Duarte
Angel Duarte

Reputation: 59

Let me tell you now: this is impossible. See those hundreds of tabs you have open? None of them have the answer, because you cannot get the name of a state. Period.

But all is not lost, developer, you're savvy. You know there are workarounds.

AnimationClip[] clips = anim.runtimeAnimatorController.animationClips; //this gets all your clips in your animator. ALL.
for (int i = 0; i < clips.Length; i++){
    print(clips[i].name); //you should create a list to store all of these.
}
Animator _aci = GetComponent<Animator>().GetCurrentAnimatorClipInfo(0);
List<theClassYouMadeForYourList> theListYouMade = new List <theClassYouMadeForYourList>(); //make sure you make a class for your list "theClassYouMadeForYourList"
for(int i = 0; i < theListYouMade.Count; i++){
    if(theListYouMade[i] == _aci[0].clip.name){//is the list item equal to the current clip name? Then do something
        print("doing something");
        break;
    }
}

I haven't tested this, but it should work. ;)

Upvotes: -5

Zhikai Xiong
Zhikai Xiong

Reputation: 397

Using AnimatorStateInfo.IsName(string name).

AnimatorStateInfo asi = GetComponent<Animator>().GetCurrentAnimatorStateInfo(0);
if(asi.IsName("Animation State Name"))
{
    // Playing "Animation State Name" now.
}

Upvotes: -1

Hossein Rashno
Hossein Rashno

Reputation: 3469

I don't think this was possible. The only good solution I can think about is to use switch statement and nameHash like this:

Animator animator = GetComponent<Animator>();

// Get the id of all state for this object
int runId = Animator.StringToHash("Run");
int jumpId = Animator.StringToHash("Jump");

AnimatorStateInfo animStateInfo = animator.GetCurrentAnimatorStateInfo(0);

switch (animStateInfo.nameHash)
{
    case runId:
        Debug.Log("Current state is Run");
        break;
    case jumpId:
        Debug.Log("Current state is Jump");
        break;
    default:
        Debug.Log("Current state is not in this list");
        break;
}

Upvotes: 11

Related Questions