最近工作量大,对接动效时间被极致压缩,动效可能因为预制调整而导致需要返工。一种情景是需要timeline中某个轨道的东西需要拆出来做成clip文件。 为了避免动效不用在clip重新k帧,于是就实现了这个工具。
该工具用于将 Unity Timeline 中的指定轨道转换为独立的 .anim 动画文件。主要功能包括:
在 Assets/xxx/Editor/ 目录下创建 TimelineToAnimationConverter.cs 文件。 完整的代码见文章末尾。
2.1 通用轨道转换菜单
代码块
[MenuItem("MyProjectTools/Integration/Timeline/Timeline Convert To Animation Clip")]
public static void ConvertTimelineTrackToAnimation()
{
foreach (var obj in Selection.objects)
{
string assetPath = AssetDatabase.GetAssetPath(obj);
if (!assetPath.EndsWith(".playable"))
{
Debug.LogWarning($"Skipping non-playable file: {assetPath}");
continue;
}
TimelineAsset timeline = AssetDatabase.LoadAssetAtPath<TimelineAsset>(assetPath);
if (timeline == null)
{
Debug.LogError($"Failed to load Timeline asset: {assetPath}");
continue;
}
ShowTrackSelectionWindow(timeline, assetPath);
}
}
2.2 轨道查找逻辑
代码块
private static TrackAsset FindTrackByName(TimelineAsset timeline, string trackName)
{
foreach (var track in timeline.GetOutputTracks())
{
if (track.name.Equals(trackName, System.StringComparison.OrdinalIgnoreCase))
{
return track;
}
foreach (var child in track.GetChildTracks())
{
if (child.name.Equals(trackName, System.StringComparison.OrdinalIgnoreCase))
{
return child;
}
}
}
return null;
}
2.3 收集所有动画轨道
代码块
private static void CollectAllAnimationTracks(IEnumerable<TrackAsset> tracks, List<TrackAsset> result)
{
foreach (var track in tracks)
{
if (track is AnimationTrack || track.GetType().Name.Contains("Animation"))
{
result.Add(track);
}
CollectAllAnimationTracks(track.GetChildTracks(), result);
}
}
2.4 轨道选择窗口
代码块
public class TrackSelectionWindow : EditorWindow
{
private TimelineAsset m_Timeline;
private string m_TimelinePath;
private List<TrackAsset> m_Tracks;
private Vector2 m_ScrollPosition;
public static void ShowWindow(TimelineAsset timeline, string timelinePath, List<TrackAsset> tracks)
{
TrackSelectionWindow window = GetWindow<TrackSelectionWindow>("Select Track to Convert");
window.m_Timeline = timeline;
window.m_TimelinePath = timelinePath;
window.m_Tracks = tracks;
window.minSize = new Vector2(400, 300);
}
private void OnGUI()
{
// 显示轨道列表,包含组名和轨道名
foreach (var track in m_Tracks)
{
string displayName = GetTrackFullPath(track);
if (GUILayout.Button(displayName, EditorStyles.miniButton))
{
ConvertTrackToAnimationClip(m_Timeline, track, m_TimelinePath);
Close();
}
}
}
private string GetTrackFullPath(TrackAsset track)
{
if (track.parent == null)
{
return track.name;
}
return $"{track.parent.name} / {track.name}";
}
}
2.5 核心转换逻辑
代码块
public static void ConvertTrackToAnimationClip(TimelineAsset timeline, TrackAsset track, string timelinePath)
{
AnimationTrack animationTrack = track as AnimationTrack;
if (animationTrack == null)
{
Debug.LogError($"Selected track is not an AnimationTrack: {track.name}");
return;
}
// 生成输出路径
string directory = Path.GetDirectoryName(timelinePath);
string fileName = Path.GetFileNameWithoutExtension(timelinePath);
string outputPath = $"{directory}/{fileName}_{track.name}.anim";
// 检查文件是否已存在
if (File.Exists(outputPath))
{
if (!EditorUtility.DisplayDialog("File Exists",
$"An animation clip already exists at:\n{outputPath}\n\nOverwrite it?",
"Yes", "No"))
{
return;
}
}
// 创建新的动画片段
AnimationClip animationClip = new AnimationClip();
animationClip.frameRate = 30;
animationClip.wrapMode = WrapMode.ClampForever;
// 遍历轨道上的所有剪辑
foreach (var clip in animationTrack.GetClips())
{
AnimationPlayableAsset clipAsset = clip.asset as AnimationPlayableAsset;
if (clipAsset != null && clipAsset.clip != null)
{
AnimationClip sourceClip = clipAsset.clip;
float startTime = (float)clip.start;
// 复制所有动画曲线
foreach (EditorCurveBinding binding in AnimationUtility.GetCurveBindings(sourceClip))
{
AnimationCurve curve = AnimationUtility.GetEditorCurve(sourceClip, binding);
if (curve != null && curve.length > 0)
{
Keyframe[] keys = curve.keys;
Keyframe[] newKeys = new Keyframe[keys.Length];
for (int i = 0; i < keys.Length; i++)
{
newKeys[i] = new Keyframe(
keys[i].time + startTime,
keys[i].value,
keys[i].inTangent,
keys[i].outTangent,
keys[i].inWeight,
keys[i].outWeight
);
newKeys[i].tangentMode = keys[i].tangentMode;
newKeys[i].weightedMode = keys[i].weightedMode;
}
AnimationCurve newCurve = new AnimationCurve(newKeys);
AnimationUtility.SetEditorCurve(animationClip, binding, newCurve);
}
}
}
}
// 处理无限剪辑
if (animationTrack.infiniteClip != null)
{
foreach (EditorCurveBinding binding in AnimationUtility.GetCurveBindings(animationTrack.infiniteClip))
{
AnimationCurve curve = AnimationUtility.GetEditorCurve(animationTrack.infiniteClip, binding);
if (curve != null && curve.length > 0)
{
AnimationUtility.SetEditorCurve(animationClip, binding, curve);
}
}
}
// 设置动画片段属性
AnimationClipSettings clipSettings = AnimationUtility.GetAnimationClipSettings(animationClip);
clipSettings.stopTime = (float)timeline.duration;
AnimationUtility.SetAnimationClipSettings(animationClip, clipSettings);
// 创建并保存资源
AssetDatabase.CreateAsset(animationClip, outputPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log($"Successfully converted track '{track.name}' to animation clip:\n{outputPath}");
EditorUtility.DisplayDialog("Conversion Complete", $"Successfully created animation clip:\n{outputPath}", "OK");
}
3.1 转换指定轨道
3.2 示例
以 main_storyline_mainview_seasontimeline.playable 为例:
代码块
using UnityEngine;
using UnityEditor;
using UnityEngine.Playables;
using UnityEngine.Timeline;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace Cyy
{
public static class TimelineToAnimationConverter
{
[MenuItem("MyProjectTools/Integration/Timeline/Timeline Convert To Animation Clip")]
public static void ConvertTimelineTrackToAnimation()
{
foreach (var obj in Selection.objects)
{
string assetPath = AssetDatabase.GetAssetPath(obj);
if (!assetPath.EndsWith(".playable"))
{
Debug.LogWarning($"Skipping non-playable file: {assetPath}");
continue;
}
TimelineAsset timeline = AssetDatabase.LoadAssetAtPath<TimelineAsset>(assetPath);
if (timeline == null)
{
Debug.LogError($"Failed to load Timeline asset: {assetPath}");
continue;
}
ShowTrackSelectionWindow(timeline, assetPath);
}
}
private static TrackAsset FindTrackByName(TimelineAsset timeline, string trackName)
{
foreach (var track in timeline.GetOutputTracks())
{
if (track.name.Equals(trackName, System.StringComparison.OrdinalIgnoreCase))
{
return track;
}
foreach (var child in track.GetChildTracks())
{
if (child.name.Equals(trackName, System.StringComparison.OrdinalIgnoreCase))
{
return child;
}
}
}
return null;
}
private static void ShowTrackSelectionWindow(TimelineAsset timeline, string timelinePath)
{
List<TrackAsset> animationTracks = new List<TrackAsset>();
CollectAllAnimationTracks(timeline.GetOutputTracks(), animationTracks);
if (animationTracks.Count == 0)
{
EditorUtility.DisplayDialog("No Animation Tracks", "The selected Timeline contains no animation tracks.", "OK");
return;
}
string[] trackNames = animationTracks.Select(t => t.name).ToArray();
TrackSelectionWindow.ShowWindow(timeline, timelinePath, animationTracks);
}
private static void CollectAllAnimationTracks(IEnumerable<TrackAsset> tracks, List<TrackAsset> result)
{
foreach (var track in tracks)
{
if (track is AnimationTrack || track.GetType().Name.Contains("Animation"))
{
result.Add(track);
}
CollectAllAnimationTracks(track.GetChildTracks(), result);
}
}
public static void ConvertTrackToAnimationClip(TimelineAsset timeline, TrackAsset track, string timelinePath)
{
AnimationTrack animationTrack = track as AnimationTrack;
if (animationTrack == null)
{
Debug.LogError($"Selected track is not an AnimationTrack: {track.name}");
return;
}
string directory = Path.GetDirectoryName(timelinePath);
string fileName = Path.GetFileNameWithoutExtension(timelinePath);
string outputPath = $"{directory}/{fileName}_{track.name}.anim";
if (File.Exists(outputPath))
{
if (!EditorUtility.DisplayDialog("File Exists",
$"An animation clip already exists at:\n{outputPath}\n\nOverwrite it?",
"Yes", "No"))
{
return;
}
}
AnimationClip animationClip = new AnimationClip();
animationClip.frameRate = 30;
animationClip.wrapMode = WrapMode.ClampForever;
foreach (var clip in animationTrack.GetClips())
{
AnimationPlayableAsset clipAsset = clip.asset as AnimationPlayableAsset;
if (clipAsset != null && clipAsset.clip != null)
{
AnimationClip sourceClip = clipAsset.clip;
float startTime = (float)clip.start;
foreach (EditorCurveBinding binding in AnimationUtility.GetCurveBindings(sourceClip))
{
AnimationCurve curve = AnimationUtility.GetEditorCurve(sourceClip, binding);
if (curve != null && curve.length > 0)
{
Keyframe[] keys = curve.keys;
Keyframe[] newKeys = new Keyframe[keys.Length];
for (int i = 0; i < keys.Length; i++)
{
newKeys[i] = new Keyframe(
keys[i].time + startTime,
keys[i].value,
keys[i].inTangent,
keys[i].outTangent,
keys[i].inWeight,
keys[i].outWeight
);
newKeys[i].tangentMode = keys[i].tangentMode;
newKeys[i].weightedMode = keys[i].weightedMode;
}
AnimationCurve newCurve = new AnimationCurve(newKeys);
AnimationUtility.SetEditorCurve(animationClip, binding, newCurve);
}
}
}
}
if (animationTrack.infiniteClip != null)
{
foreach (EditorCurveBinding binding in AnimationUtility.GetCurveBindings(animationTrack.infiniteClip))
{
AnimationCurve curve = AnimationUtility.GetEditorCurve(animationTrack.infiniteClip, binding);
if (curve != null && curve.length > 0)
{
AnimationUtility.SetEditorCurve(animationClip, binding, curve);
}
}
}
AnimationClipSettings clipSettings = AnimationUtility.GetAnimationClipSettings(animationClip);
clipSettings.stopTime = (float)timeline.duration;
AnimationUtility.SetAnimationClipSettings(animationClip, clipSettings);
AssetDatabase.CreateAsset(animationClip, outputPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log($"Successfully converted track '{track.name}' to animation clip:\n{outputPath}");
EditorUtility.DisplayDialog("Conversion Complete", $"Successfully created animation clip:\n{outputPath}", "OK");
}
[MenuItem("MyProjectTools/Integration/Timeline/Timeline Convert To Animation Clip", true)]
public static bool ValidateConvertTimelineTrackToAnimation()
{
foreach (var obj in Selection.objects)
{
string assetPath = AssetDatabase.GetAssetPath(obj);
if (assetPath.EndsWith(".playable"))
{
return true;
}
}
return false;
}
public class TrackSelectionWindow : EditorWindow
{
private TimelineAsset m_Timeline;
private string m_TimelinePath;
private List<TrackAsset> m_Tracks;
private Vector2 m_ScrollPosition;
public static void ShowWindow(TimelineAsset timeline, string timelinePath, List<TrackAsset> tracks)
{
TrackSelectionWindow window = GetWindow<TrackSelectionWindow>("Select Track to Convert");
window.m_Timeline = timeline;
window.m_TimelinePath = timelinePath;
window.m_Tracks = tracks;
window.minSize = new Vector2(400, 300);
}
private void OnGUI()
{
if (m_Tracks == null || m_Tracks.Count == 0)
{
GUILayout.Label("No animation tracks found in the selected Timeline.");
return;
}
GUILayout.Label("Select a track to convert to animation clip:", EditorStyles.boldLabel);
m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);
foreach (var track in m_Tracks)
{
string displayName = GetTrackFullPath(track);
if (GUILayout.Button(displayName, EditorStyles.miniButton))
{
ConvertTrackToAnimationClip(m_Timeline, track, m_TimelinePath);
Close();
}
}
EditorGUILayout.EndScrollView();
}
private string GetTrackFullPath(TrackAsset track)
{
if (track.parent == null)
{
return track.name;
}
return $"{track.parent.name} / {track.name}";
}
}
}
}
免责声明:本文系网络转载或改编,未找到原创作者,版权归原作者所有。如涉及版权,请联系删