Hi,
Is there any way to get the default state of an animator ? At least his name ?
My wish is to reset an animator automatically when the player want to restart the game or when he dies. I mean I want to do it in code.
Thx!
Hi,
Is there any way to get the default state of an animator ? At least his name ?
My wish is to reset an animator automatically when the player want to restart the game or when he dies. I mean I want to do it in code.
Thx!
Usually, if you don’t change it, default state is the first state in the state machine. So, imagining that your AnimatorController is saved on a varaible called _ac, you can access the first state by:
with this you can do what you need with that state.
If you want to find it by name, you can do something similar to this:
foreach (var variable in _ac.layers[0].stateMachine.states){
if (variable.state.name.Equals("Your-State-Name")){
// Do something here
}
}
It’s astonishing to me that Unity’s API design could suck at API design as much as it does… especially given that this is their second stab at it (and the first was superior in many ways).
But… taking a breath. I have the same desire as the OP, to replay the first (default) state. I don’t have a reference to n AnimatorController; I have the Animator component. It has a runtimeAnimatorController property, but that doesn’t have a layers property (it has barely anything).
So. Given an Animator, how the heck do you find the name of the first state, or otherwise tell it “do what you did at startup again”? (I did try playing the “Entry” state but that didn’t work.)
To actually answer your question:
There is another (better) approach though: stop using animator controllers and use my Animancer plugin instead (link in my signature). It lets you control everything using scripts so if you want a function to return to the default animation you can just implement one to do exactly that. For me that’s usually an Idle script so I just have a ReturnToIdle function in my base CreatureState class which tells the creature’s state machine to enter the Idle state.
Yeah, my need here is at runtime, not in the editor. We “solved” it by requiring the default state to always be called “Default”.
But your Animancer plugin sounds like a big improvement. I hate having to create AnimatorControllers all over the place just to play a simple animation. I will definitely check that out!
Just to follow up (since somebody pinged me on this today)… I did end up getting @Kybernetik 's Animancer plugin, and now use it in multiple projects. It has been great. Much easier to use, and more flexible than Unity’s approach.