Ice*_*ain 1 animation runtime unity-game-engine
我正在开发一个可以在运行时修改动画的小程序(例如,当您运行得更快时,动画不仅播放速度更快,而且移动幅度更大)。所以我需要获取现有动画,更改其值,然后将其发回。
我发现有趣的是我可以为动画设置一条新曲线,但我无法访问我已经拥有的曲线。所以我要么写一个文件来存储我的动画曲线(例如作为文本文件),要么我想办法在启动时读取动画。
我试着用
AnimationUtility.GetCurveBindings(AnimationCurve);
Run Code Online (Sandbox Code Playgroud)
它在我的测试中有效,但在某些页面上它说这是一个“编辑器代码”,如果我将项目构建到独立程序中,它将不再起作用。真的吗?如果是这样,有没有办法在运行时获得曲线?
感谢 Benjamin Zach 的 clearify 和 TehMightyPotato 的建议,我想保留在运行时修改动画的想法。因为它可以适应更多情况imo。
我现在的想法是编写一段编辑器代码,可以在编辑器中读取曲线并将有关曲线(关键帧)的所有必要信息输出到文本文件中。然后在运行时读取该文件并创建新曲线以覆盖现有曲线。我将把这个问题保留几天,然后检查它,看看是否有人对此有更好的想法。
如前所述,已经AnimationUtility
属于UnityEditor
命名空间。整个命名空间在构建中被完全剥离,其中任何内容都不会在最终应用程序中可用,但只能在 Unity 编辑器中使用。
为了将所有需要的信息存储到文件中,您可以有一个脚本,用于在使用例如构建之前在编辑器中序列化您的特定动画曲线BinaryFormatter.Serialize
。然后在运行时您可以BinaryFormatter.Deserialize
再次用于返回信息列表。
如果您希望它更具可编辑性,当然也可以使用例如JSON或XML
更新:一般停止使用BinaryFormatter
!
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using Object = UnityEngine.Object;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class AnimationCurveManager : MonoBehaviour
{
[Serializable]
public sealed class ClipInfo
{
public int ClipInstanceID;
public List<CurveInfo> CurveInfos = new List<CurveInfo>();
// default constructor is sometimes required for (de)serialization
public ClipInfo() { }
public ClipInfo(Object clip, List<CurveInfo> curveInfos)
{
ClipInstanceID = clip.GetInstanceID();
CurveInfos = curveInfos;
}
}
[Serializable]
public sealed class CurveInfo
{
public string PathKey;
public List<KeyFrameInfo> Keys = new List<KeyFrameInfo>();
public WrapMode PreWrapMode;
public WrapMode PostWrapMode;
// default constructor is sometimes required for (de)serialization
public CurveInfo() { }
public CurveInfo(string pathKey, AnimationCurve curve)
{
PathKey = pathKey;
foreach (var keyframe in curve.keys)
{
Keys.Add(new KeyFrameInfo(keyframe));
}
PreWrapMode = curve.preWrapMode;
PostWrapMode = curve.postWrapMode;
}
}
[Serializable]
public sealed class KeyFrameInfo
{
public float Value;
public float InTangent;
public float InWeight;
public float OutTangent;
public float OutWeight;
public float Time;
public WeightedMode WeightedMode;
// default constructor is sometimes required for (de)serialization
public KeyFrameInfo() { }
public KeyFrameInfo(Keyframe keyframe)
{
Value = keyframe.value;
InTangent = keyframe.inTangent;
InWeight = keyframe.inWeight;
OutTangent = keyframe.outTangent;
OutWeight = keyframe.outWeight;
Time = keyframe.time;
WeightedMode = keyframe.weightedMode;
}
}
// I know ... singleton .. but what choices do we have? ;)
private static AnimationCurveManager _instance;
public static AnimationCurveManager Instance
{
get
{
// lazy initialization/instantiation
if(_instance) return _instance;
_instance = FindObjectOfType<AnimationCurveManager>();
if(_instance) return _instance;
_instance = new GameObject("AnimationCurveManager").AddComponent<AnimationCurveManager>();
return _instance;
}
}
// Clips to manage e.g. reference these via the Inspector
public List<AnimationClip> clips = new List<AnimationClip>();
// every animation curve belongs to a specific clip and
// a specific property of a specific component on a specific object
// for making this easier lets simply use a combined string as key
private string CurveKey(string pathToObject, Type type, string propertyName)
{
return $"{pathToObject}:{type.FullName}:{propertyName}";
}
public List<ClipInfo> ClipCurves = new List<ClipInfo>();
private void Awake()
{
if(_instance && _instance != this)
{
Debug.LogWarning("Multiple Instances of AnimationCurveManager! Will ignore this one!", this);
return;
}
_instance = this;
DontDestroyOnLoad(gameObject);
// load infos on runtime
LoadClipCurves();
}
#if UNITY_EDITOR
// Call this from the ContextMenu (or later via editor script)
[ContextMenu("Save Animation Curves")]
private void SaveAnimationCurves()
{
ClipCurves.Clear();
foreach (var clip in clips)
{
var curveInfos = new List<CurveInfo>();
ClipCurves.Add(new ClipInfo(clip, curveInfos));
foreach (var binding in AnimationUtility.GetCurveBindings(clip))
{
var key = CurveKey(binding.path, binding.type, binding.propertyName);
var curve = AnimationUtility.GetEditorCurve(clip, binding);
curveInfos.Add(new CurveInfo(key, curve));
}
}
// create the StreamingAssets folder if it does not exist
try
{
if (!Directory.Exists(Application.streamingAssetsPath))
{
Directory.CreateDirectory(Application.streamingAssetsPath);
}
}
catch (IOException ex)
{
Debug.LogError(ex.Message);
}
// create a new file e.g. AnimationCurves.dat in the StreamingAssets folder
var fileStream = new FileStream(Path.Combine(Application.streamingAssetsPath, "AnimationCurves.dat"), FileMode.Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
var formatter = new BinaryFormatter();
try
{
formatter.Serialize(fileStream, ClipCurves);
}
catch (SerializationException e)
{
Debug.LogErrorFormat(this, "Failed to serialize. Reason: {0}", e.Message);
}
finally
{
fileStream.Close();
}
AssetDatabase.Refresh();
}
#endif
private void LoadClipCurves()
{
var filePath = Path.Combine(Application.streamingAssetsPath, "AnimationCurves.dat");
if (!File.Exists(filePath))
{
Debug.LogErrorFormat(this, "File \"{0}\" not found!", filePath);
return;
}
var fileStream = new FileStream(filePath, FileMode.Open);
try
{
var formatter = new BinaryFormatter();
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
ClipCurves = (List<ClipInfo>)formatter.Deserialize(fileStream);
}
catch (SerializationException e)
{
Debug.LogErrorFormat(this, "Failed to deserialize. Reason: {0}", e.Message);
}
finally
{
fileStream.Close();
}
}
// now for getting a specific clip's curves
public AnimationCurve GetCurve(AnimationClip clip, string pathToObject, Type type, string propertyName)
{
// either not loaded yet or error -> try again
if (ClipCurves == null || ClipCurves.Count == 0) LoadClipCurves();
// still null? -> error
if (ClipCurves == null || ClipCurves.Count == 0)
{
Debug.LogError("Apparantly no clipCurves loaded!");
return null;
}
var clipInfo = ClipCurves.FirstOrDefault(ci => ci.ClipInstanceID == clip.GetInstanceID());
// does this clip exist in the dictionary?
if (clipInfo == null)
{
Debug.LogErrorFormat(this, "The clip \"{0}\" was not found in clipCurves!", clip.name);
return null;
}
var key = CurveKey(pathToObject, type, propertyName);
var curveInfo = clipInfo.CurveInfos.FirstOrDefault(c => string.Equals(c.PathKey, key));
// does the curve key exist for the clip?
if (curveInfo == null)
{
Debug.LogErrorFormat(this, "The key \"{0}\" was not found for clip \"{1}\"", key, clip.name);
return null;
}
var keyframes = new Keyframe[curveInfo.Keys.Count];
for (var i = 0; i < curveInfo.Keys.Count; i++)
{
var keyframe = curveInfo.Keys[i];
keyframes[i] = new Keyframe(keyframe.Time, keyframe.Value, keyframe.InTangent, keyframe.OutTangent, keyframe.InWeight, keyframe.OutWeight)
{
weightedMode = keyframe.WeightedMode
};
}
var curve = new AnimationCurve(keyframes)
{
postWrapMode = curveInfo.PostWrapMode,
preWrapMode = curveInfo.PreWrapMode
};
// otherwise finally return the AnimationCurve
return curve;
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以做一些像ee
AnimationCurve originalCurve = AnimationCurvesManager.Instance.GetCurve(
clip,
"some/relative/GameObject",
typeof<SomeComponnet>,
"somePropertyName"
);
Run Code Online (Sandbox Code Playgroud)
pathToObject
如果属性/组件附加到根对象本身,则第二个参数是一个空字符串。否则,它会像往常一样在 Unity 的层次结构路径中给出,例如“ChildName/FurtherChildName”。
现在您可以更改值并在运行时分配新曲线。
在运行时,您可以使用animator.runtimeanimatorController
它来检索RuntimeAnimatorController
引用。
它有一个属性animationClips
,它返回AnimationClip
分配给这个控制器的所有s。
然后您可以使用例如LinqFirstOrDefault
来AnimationClip
按名称查找特定的名称,并最终使用AnimationClip.SetCurve
将新的动画曲线分配给某个组件和属性。
例如类似的东西
// you need those of course
string clipName;
AnimationCurve originalCurve = AnimationCurvesManager.Instance.GetCurve(
clip,
"some/relative/GameObject",
typeof<SomeComponnet>,
"somePropertyName"
);
// TODO
AnimationCurve newCurve = SomeMagic(originalCurve);
// get the animator reference
var animator = animatorObject.GetComponent<Animator>();
// get the runtime Animation controller
var controller = animator.runtimeAnimatorController;
// get all clips
var clips = controller.animationClips;
// find the specific clip by name
// alternatively you could also get this as before using a field and
// reference the according script via the Inspector
var someClip = clips.FirstOrDefault(clip => string.Equals(clipName, clip.name));
// was found?
if(!someClip)
{
Debug.LogWarningFormat(this, "There is no clip called {0}!", clipName);
return;
}
// assign a new curve
someClip.SetCurve("relative/path/to/some/GameObject", typeof(SomeComponnet), "somePropertyName", newCurve);
Run Code Online (Sandbox Code Playgroud)
注意:在智能手机上输入所以没有保修!但我希望这个想法变得清晰......
还要查看AnimationClip.SetCurve
? 您可能希望在您的特定用例中使用该Animation
组件而不是Animator
。
归档时间: |
|
查看次数: |
4871 次 |
最近记录: |