因項(xiàng)目需要,人物30多個(gè)窗悯,每個(gè)人物動(dòng)畫(huà)以及命名都是一樣区匣。新版的動(dòng)畫(huà)系統(tǒng)Mecanim,支持連線(xiàn)之類(lèi)蒋院,想在新項(xiàng)目中使用亏钩。但是讓策劃一個(gè)個(gè)手動(dòng)去連線(xiàn),設(shè)置觸發(fā)條件太麻煩了也容易出錯(cuò)欺旧。(初步我們有4個(gè)動(dòng)作 "walk", "idle", "attack", "skill"姑丑,四個(gè)動(dòng)作可以直接相互切換)
網(wǎng)上沒(méi)找到類(lèi)似的代碼。辞友。于是寫(xiě)了個(gè)簡(jiǎn)單的插件來(lái)處理栅哀。直接上代碼震肮。。這個(gè)就自動(dòng)連線(xiàn)和設(shè)置里面的條件了留拾。
先搜索整個(gè)目錄下的fbx文件(動(dòng)作和模型做到一起去了)戳晌,然后根據(jù)制定的幾個(gè)動(dòng)作,自動(dòng)生成狀態(tài)機(jī)间驮,包括設(shè)置好觸發(fā)條件躬厌。
Paste_Image.png
自動(dòng)生成的生成的動(dòng)畫(huà)狀態(tài)機(jī)
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
public class AutoAnimatorCtl : Editor
{
[MenuItem("test/AutoAnimatorCtl")]
static void batchAnimatorCtl()
{
string dirPath = "Assets/Media/Character/Model/";
foreach (string path in Directory.GetFiles(dirPath))
{
if (System.IO.Path.GetExtension(path) == ".FBX")
{
createAnimatorCtl(path);
}
}
}
static bool isUniqueState(string str)
{
string[] states = { "walk", "idle", "attack", "skill" };
foreach (string state in states)
{
if (str == state)
return true;
}
return false;
}
//檢查fbx里面動(dòng)畫(huà)的完整性
static bool checkFullAnimation(Object[] objs)
{
string[] clipName = { "walk", "idle", "attack", "skill" };
//Object[] objs = AssetDatabase.LoadAllAssetsAtPath(path);
int num = 0;
foreach (Object obj in objs)
{
if(obj is AnimationClip && isUniqueState(obj.name))
{
num = num + 1;
}
}
if (num == clipName.Length)
return true;
return false;
}
static void createAnimatorCtl(string path)
{
path = path.Replace("\\", "/");
path = path.Replace(".FBX", ".fbx");
string acPath = path.Replace(".fbx", ".controller");
string prePath = path.Replace(".fbx", ".prefab");
Object[] objs = AssetDatabase.LoadAllAssetsAtPath(path);
var animatorController = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(acPath);
var layer = animatorController.layers[0];
var anmationStateMachine = layer.stateMachine;
List<UnityEditor.Animations.AnimatorState> states = new List<UnityEditor.Animations.AnimatorState>();
foreach (Object obj in objs)
{
if (obj is AnimationClip && isUniqueState(obj.name) == true)
{
Debug.Log(obj.name + " is clip");
var state = anmationStateMachine.AddState(obj.name);
states.Add(state);
state.motion = obj as Motion;
}
}
animatorController.AddParameter("walk", AnimatorControllerParameterType.Bool);
animatorController.AddParameter("skill", AnimatorControllerParameterType.Bool);
animatorController.AddParameter("attack", AnimatorControllerParameterType.Bool);
animatorController.AddParameter("idle", AnimatorControllerParameterType.Bool);
for(int i = 0; i< states.Count;i++)
{
for(int j = 0; j < states.Count; j++)
{
if(i != j)
{
var anstateTras = states[i].AddTransition(states[j], false);
anstateTras.AddCondition(UnityEditor.Animations.AnimatorConditionMode.If, 0, states[j].name);
}
}
if(states[i].name == "idle")
{
anmationStateMachine.defaultState = states[i];
}
}
}
}