在某些情況下,我們需要把物體的運動狀態,材質變化等信息錄製下來存儲到Clip中。比如說,用到ITween、DoTween等插件控制物體運動,然後想把運動的過程記錄下來。就需要在Editor Runtime下進行一些操作來達到我們的目的。
所幸Unity提供了一套還比較完善的API供我們使用。接下來就介紹一下步驟。
首先我們需要知道Unity支持的API,叫做GameObjectRecorder(類庫是:UnityEditor.Animations,Unity 2018測試)。接下來只需要三步就可以完成。
-
創建GameObjectRecorder類型的實例。
-
調用GameObjectRecorder實例的方法 BindComponentOfType(GameObject , )綁定需要錄製的組件,然後調用TakeSnapshot(Time.deltaTime),進行錄製。這裏要注意GameObject參數是錄製Clip的根節點,如果要錄製的動畫層級很多,一定要把這個參數設爲根節點。不然錄製的Clip層級不對。
-
調用GameObjectRecorder實例的方法SaveToClip(AnimationClip),把綁定的幀存儲在Clip中。
代碼如下:
using UnityEngine;
using UnityEditor.Animations;
public class RecordTransformHierarchy : MonoBehaviour
{
public AnimationClip clip;
private GameObjectRecorder m_Recorder;
void Start()
{
// Create recorder and record the script GameObject.
m_Recorder = new GameObjectRecorder(gameObject);
// Bind all the Transforms on the GameObject and all its children.
//這裏的Bind操作,可以綁定各種UnityEngine的類型,比如MeshRender之類,
//綁定之後就可以記錄這個類型的值了。這裏參數還需要注意,gameObject是Root節點,
//如果要錄製的物體有很多層級的話,最好參數設置爲根節點。不然層級信息不對在Clip中無法播放。
m_Recorder.BindComponentsOfType<Transform>(gameObject, true);
}
void LateUpdate()
{
if (clip == null)
return;
// Take a snapshot and record all the bindings values for this frame.
m_Recorder.TakeSnapshot(Time.deltaTime);
}
void OnDisable()
{
if (clip == null)
return;
if (m_Recorder.isRecording)
{
// Save the recorded session to the clip.
m_Recorder.SaveToClip(clip);
}
}
}
準備好代碼之後,可以把代碼直接綁定到要錄製的物體上,然後Play。之後就可以錄製物體的動畫文件了。下邊是錄製了Meshrenderer的BlendShape信息:
OK,到這裏就完成了錄製某個物體的運動、材質變化、等等一切可以被錄製成動畫的信息。有問題請留言哦。