Have a look at different approach on Animation using "SimpleAnimation" via new Unity's Playable system.
Introducing the Simple Animation Component (Unity Blog)
Under the hood it hacks the way using animator to play animation while controlling clip and state name from Playables, using new API set
But now you can add states easier by script since you are dealing with playables not RuntimeAnimatorController and their messy state system. This is how it looks like when you use it on your end:
// Assumes following variables
SimpleAnimation m_CustomAnimationPlayable; // Via inspector or added on runtime
AnimationClip clip, clip2; // Via inspector or other mean
// Example on creating
m_CustomAnimationPlayable.AddState( clip, "run" );
m_CustomAnimationPlayable.AddState( clip2, "attack" );
// Example on playing
m_CustomAnimationPlayable.Play( "run" );
m_CustomAnimationPlayable.PlayQueued( "run", QueueMode );
m_CustomAnimationPlayable.CrossFade( "run", 1.0f ); // crossfade length
It need quite a bit of initial setup but this official github will provide most boilerplate code for you:
Official Unity Git Hub for SimpleAnimation
Here is outline of setting up
- You still need pre-constructed Animator in Unity editor but it could be almost blank or most simple one. This allows you to set other useful field in Animator such as avatar setup.
- Add "SimpleAnimation" component to the game object that has animator installed.
- Call SimpleAnimation.AddState( clip, name ) to add your own state. You don't have to even define transition. Of course, you need your own way to provide list of AnimationClip to use, it could be drag n drop field in your component or ScriptableObject contains animation database of some kind. Or if you want totally "no-drag-drop", your solution would limit to
Resources API and alike. (Refer to @Phillips answer)
- Play any state or crossfade using SimpleAnimationPlay( statename );
Key point VS legacy Animation component
- ⌾ Not require marking AnimationClip as Legacy.
- ⌾ You can use Animator (Mechanim) important features such as Avatar (bone re-targetting), and possibly (I'm not sure) root motion.
- △ Code amount to setup is around the same as using Legacy Animation.
Be discreet on Resources folder (!!)
Resources API has been a good accessible way for loading thing on runtime.
- BUT Resource folder incurs memory and build performance. For best practice, use it with discreet. Do not dump everything there.
- Further in-depth read: Asset Bundles vs. Resources: A Memory Showdown
- Further in-depth read: Assets, Resources and AssetBundles
- What is worse than Unity's own best practice explicitly said
Don't use it.?
There is also AnimatorOverrideController
Keep in mind that there is also another approach AnimatorOverrideController, which is also possible to do on script runtime level. But this is leaning more toward scenario such as having several actors with exactly same state machine but with different AnimationClip override for each state.