Skip to content

Instantly share code, notes, and snippets.

@to-osaki
Last active April 12, 2022 08:10
Show Gist options
  • Save to-osaki/fad8628be446abdfa2ccf9fb64ed18d8 to your computer and use it in GitHub Desktop.
Save to-osaki/fad8628be446abdfa2ccf9fb64ed18d8 to your computer and use it in GitHub Desktop.

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";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment