Adding State Machine Behaviour via Script C#

How do I add a Behaviour to a State Machine?
I am using this:

AnimatorState newState = new AnimatorState();
newState.AddStateMachineBehaviour<StateScript>();

StateScript is my behavior script file.

Howerver I am getting this error:

AddAssetToSameFile failed because the other asset j is not persistent

Anyone knows why and how to solve it?

Thanks.

Did you ever figure this out ? same issue…
I assume its in editor script so the new state is not added to the parent asset as a permanent object, did you figure out how to ?

yeah exactly, newState is not persisted, normally you would add an AnimatorState into a controller which is persisted

take a look at this example

after adding an animator state you can add your state machine behaviour

1 Like

Thanks.
Yeah figured it out… Need to use Animator.runTimeAnimatorControllor, then from there get the Asset from AssetDatabase, and can edit that.
UnityEditor.Animations.AnimatorController AnimContr = AssetDatabase.LoadAssetAtPath(AssetDatabase.GetAssetPath(MyAnimator.runtimeAnimatorController));

1 Like