Unity 代码生成动画控制器
最近项目中有大量的动画需要在unity中查看,自己一个个托太麻烦,写了段代码自动生成。
using System.Collections; using UnityEditor.Animations; using UnityEngine; using UnityEditor; using System.IO; using System.Collections.Generic; using System; public class Spader : Editor {
// 递归的遍历获取path下的fbx文件 static List<string> RecursiveGetFiles(string path) { var ls = new List<string>(); var dirs = Directory.GetDirectories(path); foreach (var d in dirs) ls.AddRange(RecursiveGetFiles(d)); ls.AddRange(Directory.GetFiles(path, "*.fbx")); return ls; } [MenuItem("Animator/Create Animator Controller")] static void CreateController() { // Creates the controller var controller = AnimatorController.CreateAnimatorControllerAtPath("Assets/Model/Motion.controller"); // Get all anim file var path = Application.dataPath + "/Resources/"; var allFiles = RecursiveGetFiles(path); var allClips = new List<AnimationClip>(); foreach (var f in allFiles) { var fPath = f.Substring(Application.dataPath.Length); var fbx = AssetDatabase.LoadAllAssetsAtPath("Assets" + fPath); foreach (var ob in fbx) { if(ob.GetType() == typeof(AnimationClip)) if(! ob.name.StartsWith("__preview")) allClips.Add(ob as AnimationClip); } } allClips.Sort((x, y)=> { if (x.name == "Idle01") return -1; else return 0; }); // Add parameters foreach (var clip in allClips) controller.AddParameter(clip.name, AnimatorControllerParameterType.Trigger); // Add states and transitions var rootStateMachine = controller.layers[0].stateMachine; foreach (var clip in allClips) { var state = rootStateMachine.AddState(clip.name); state.motion = clip; var transition = rootStateMachine.AddAnyStateTransition(state); transition.AddCondition(AnimatorConditionMode.If, 0.0f, clip.name); transition.canTransitionToSelf = false; if (clip.name == "Idle01") transition.canTransitionToSelf = true; } } }