Generate AnimatorController by editor scripting
[SerializeField]
RuntimeAnimatorController ControllerAsset;
[ContextMenu("Generate")]
void Generate()
{
var controller = ControllerAsset != null ?
ControllerAsset as AnimatorController :
AnimatorController.CreateAnimatorControllerAtPath("GeneratedController.controller");
controller.AddParameter("Mode", AnimatorControllerParameterType.Int);
controller.AddParameter("Walk", AnimatorControllerParameterType.Bool);
var baseLayer = controller.layers.First(l => l.name == "Base Layer");
var baseStateMachine = baseLayer.stateMachine;
var subStateMachine = baseStateMachine.AddStateMachine("OutGame", new Vector3(300, 0));
subStateMachine.entryPosition = new Vector2(200, 0);
var idle = subStateMachine.AddState("Idle", new Vector2(400, 100));
idle.tag = "Idle";
idle.motion = IdleAnimation;
var walk = subStateMachine.AddState("Walk", new Vector2(400, 200));
walk.motion = WalkAnimation;
subStateMachine.entryPosition = new Vector2(0, 0);
idle.AddTransition(walk).AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, "Walk");
idle.AddExitTransition().AddCondition(UnityEditor.Animations.AnimatorConditionMode.NotEqual, 1, "Mode");
walk.AddTransition(idle, defaultExitTime: true).AddCondition(UnityEditor.Animations.AnimatorConditionMode.IfNot, 0, "Walk");
walk.AddTransition(idle).AddCondition(UnityEditor.Animations.AnimatorConditionMode.NotEqual, 1, "Mode");
UnityEditor.EditorUtility.SetDirty(controller);
}
new AnimationStateしたものをAddStateすると、Stateがアセットとして保存されない。 https://forum.unity.com/threads/animation-controller-transitions-missing-and-not-saved.432127/
var state = new AnimatorState { name = "State", tag = "Idle" };
stateMachine.AddState(state, Vector2.zero); // state is not serialized
AddStateで生成したStateはAddObjectToAssetされているので、保存される。
var state = baseStateMachine.AddState("state", Vector2.zero);
state.tag = "Idle";