Files
PrinceOfGlory/Assets/Editor/ShirakaTools/FBX_Auto_Animator.cs
kridoo 6e91a0c7f0 111
2025-09-15 17:32:08 +08:00

90 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using UnityEditor;
using UnityEditor.Animations;
using System.IO;
using System.Linq;
public class FbxBatchSpawner : EditorWindow
{
private DefaultAsset fbxFolder;
[MenuItem("Tools/ShirakaTool/FBX_Auto_Animator")]
public static void ShowWindow()
{
GetWindow<FbxBatchSpawner>("批量FBX导入");
}
private void OnGUI()
{
GUILayout.Label("选择包含 FBX 的文件夹", EditorStyles.boldLabel);
fbxFolder = (DefaultAsset)EditorGUILayout.ObjectField("FBX文件夹", fbxFolder, typeof(DefaultAsset), false);
if (GUILayout.Button("导入到场景"))
{
if (fbxFolder != null)
ProcessFbxFolder(AssetDatabase.GetAssetPath(fbxFolder));
else
Debug.LogWarning("请先选择一个文件夹!");
}
}
private void ProcessFbxFolder(string folderPath)
{
string[] fbxPaths = Directory.GetFiles(folderPath, "*.fbx", SearchOption.AllDirectories);
foreach (var fbxPath in fbxPaths)
{
string unityPath = fbxPath.Replace(Application.dataPath, "Assets");
GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(unityPath);
if (prefab == null) continue;
// 尝试加载动画剪辑(不是通过 AnimationUtility
var allAssets = AssetDatabase.LoadAllAssetsAtPath(unityPath);
var clips = allAssets
.OfType<AnimationClip>()
.Where(c => !c.name.StartsWith("__preview__")) // 排除 Unity 自动生成的预览剪辑
.ToArray();
if (clips.Length == 0)
{
Debug.LogWarning($"未找到动画: {unityPath}");
continue;
}
// 实例化
GameObject instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
instance.name = prefab.name;
// 创建 Animator Controller
string controllerPath = Path.Combine(Path.GetDirectoryName(unityPath), prefab.name + "_Auto.controller");
controllerPath = controllerPath.Replace("\\", "/");
AnimatorController controller = AnimatorController.CreateAnimatorControllerAtPath(controllerPath);
// 添加第一个动画状态
var state = controller.layers[0].stateMachine.AddState("Default");
state.motion = clips[0];
state.speed = 1;
state.name = clips[0].name;
// 设为默认状态
controller.layers[0].stateMachine.defaultState = state;
// 设置动画为循环
var settings = AnimationUtility.GetAnimationClipSettings(clips[0]);
settings.loopTime = true;
AnimationUtility.SetAnimationClipSettings(clips[0], settings);
// 挂 Animator
Animator animator = instance.GetComponent<Animator>();
if (animator == null)
animator = instance.AddComponent<Animator>();
animator.runtimeAnimatorController = controller;
Debug.Log($"处理完成: {prefab.name}");
}
Debug.Log($"全部完成,共导入 {fbxPaths.Length} 个 FBX。");
}
}