-
Notifications
You must be signed in to change notification settings - Fork 5
/
AnimationPreviewPlayer.cs
80 lines (61 loc) · 2.92 KB
/
AnimationPreviewPlayer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
namespace EditorScripts {
[InitializeOnLoad]
public static class AnimationPreviewPlayer {
private const BindingFlags PRIVATE_FIELD_BINDING_FLAGS = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField;
private const BindingFlags PUBLIC_FIELD_BINDING_FLAGS = BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField;
private const BindingFlags PUBLIC_PROPERTY_BINDING_FLAGS = BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty;
private static Type animationClipEditorType;
private static Type avatarPreviewType;
private static Type timeControlType;
private static Object selectedObject;
private static bool shouldFindTimeControl;
static AnimationPreviewPlayer () {
animationClipEditorType = Type.GetType("UnityEditor.AnimationClipEditor,UnityEditor");
avatarPreviewType = Type.GetType("UnityEditor.AvatarPreview,UnityEditor");
timeControlType = Type.GetType("UnityEditor.TimeControl,UnityEditor");
}
private static void Update () {
if (Selection.activeObject != selectedObject) {
selectedObject = Selection.activeObject;
if (selectedObject is AnimationClip) {
shouldFindTimeControl = true;
}
else if (selectedObject is GameObject) {
var assetPath = AssetDatabase.GetAssetPath(selectedObject);
if (!string.IsNullOrWhiteSpace(assetPath)) {
foreach (var child in AssetDatabase.LoadAllAssetsAtPath(assetPath)) {
if (child is AnimationClip) {
shouldFindTimeControl = true;
break;
}
}
}
}
return;
}
if (shouldFindTimeControl) {
var animationClipEditor = Resources.FindObjectsOfTypeAll(animationClipEditorType).FirstOrDefault();
if (animationClipEditor == null) return;
var avatarPreview = animationClipEditorType.GetField("m_AvatarPreview", PRIVATE_FIELD_BINDING_FLAGS)?.GetValue(animationClipEditor);
if (avatarPreview == null) return;
var timeControl = avatarPreviewType.GetField("timeControl", PUBLIC_FIELD_BINDING_FLAGS)?.GetValue(avatarPreview);
if (timeControl == null) return;
shouldFindTimeControl = false;
var playingProperty = timeControlType.GetProperty("playing", PUBLIC_PROPERTY_BINDING_FLAGS);
if (playingProperty == null) return;
playingProperty.SetValue(timeControl, true);
}
}
[InitializeOnLoadMethod, UsedImplicitly]
private static void SubscribeToUpdate () {
EditorApplication.update += Update;
}
}
}