1. 程式人生 > >Unity流水賬5:Animation Events

Unity流水賬5:Animation Events

你可以通過使用Animation Events來增加Animation Clips的有用性,它允許你在時間軸中指定的點呼叫物件指令碼中的函式。 Animation Event呼叫的函式還可以選擇接受一個引數。引數可以是浮點數、字串、int或物件引用,也可以是Animation Event物件。AnimationEvent物件有成員變數,他們允許一個浮點數、字串、整數和物件引用同時被傳遞到函式中,以及觸發函式呼叫的事件的其他資訊。 若要在當前播放頭位置向clip新增動畫事件,請單擊事件按鈕。將對話時間新增到動畫中的任意點。在希望觸發事件的點雙擊事件行。新增後,可以拖動滑鼠重新定位事件。要刪除事件,請選擇它並按下delete鍵,或右鍵單擊它並選擇delete event; AnimationEditorEventLine

Animation Event允許將資料新增到匯入的剪輯中,該剪輯決定了某些動作合適與動畫同步發生。例如,對於一個動畫角色,你可能想要新增一些事件來說明應該在什麼時候播放指令碼聲。 新增事件時,Inspector視窗會顯示幾個欄位。這些欄位允許你指定要呼叫的函式的名稱,以及要傳遞給它的引數的值。 AnimationEventInspector 新增到clips中的事件顯示為事件行中的標記。把滑鼠放在標記上,以顯示帶有函式名和引數值的工具提示。 AnimationEditorEventTooltip 你可以在時間軸中選擇和操作多個事件。 要在時間軸中選擇多個事件,按住Shift鍵並逐個選擇事件標記,將它們新增到你的選擇中。你還可以在它們之間拖動選擇框,單擊並拖動事件標記區域,如下所示: AnimationEditorMultipleEventSelection
例子: 這個例子演示瞭如何向一個簡單的GameObject新增動畫事件。在執行所有步驟時,Cube在Play模式中沿x軸向前和向後移動,事件訊息在0.8秒後每間隔1秒在控制檯顯示一次(包括0.8秒)。 這個示例需要一個帶有PrintEvent()函式的小指令碼。此函式列印一個除錯訊息,其中包含一個字串(“called at:”) and the time:

using UnityEngine;
public class ExampleClass : MonoBehaviour
{
    public void PrintEvent(string s)
    {
        Debug.Log("PrintEvent: "
+ s + " called at: " + Time.time); } }

用示例程式碼建立一個指令碼檔案,並將其放在你的專案資料夾中(右鍵單擊Unity中的Project視窗並選擇Create->C# Script,然後將上面的程式碼示例複製貼上到檔案中儲存)。 在Unity中建立一個Cube GameObject(選單:GameObject->3D Object->Cube).要向它新增你的新指令碼,可以將指令碼從Project視窗拖放到Inspector視窗中。 選擇Cube然後開啟Animation視窗(選單:Window->Animation)。設定x座標的位置曲線。 AnimationEventExample 接下來,將x座標的動畫設定為大約0.4,然後在一秒內回到0,然後大約在0.8秒內建立一個動畫事件。按下Play以執行動畫。

程式碼示例: UI設定 動畫設定

using UnityEngine;
public class AnimationEventTest:MonoBehaviour
{
    public void PrintFloat(float theValue)
    {
        Debug.Log("PrintFloat is called with a value of " + theValue + ":" + Time.time);
    }
}

動態新增動畫事件: UI設定

using UnityEngine;
public class AnimationEventTest:MonoBehaviour
{
    private Animator mAnimator;
    private RuntimeAnimatorController mRuntimeAnimatorController;
    private AnimationClip[] clipArray;
    void Start()
    {
        mAnimator = GetComponent<Animator>();
        mRuntimeAnimatorController = mAnimator.runtimeAnimatorController;
        clipArray = mRuntimeAnimatorController.animationClips;
        int clipCount = clipArray.Length;
        for(int i = 0; i < clipCount; ++i)
        {
            for(clipArray[i].name = "test")
            {
                AnimationEvent animationEvent = new AnimationEvent();
                animationEvent.functionName = "PrintFloat";
                //動畫末尾
                animationEvent.time = clipArray[i].length;
                clipArray[i].AddEvent(animationEvent);
            }
        }
    }
    public void PrintFloat(float theValue)
    {
        Debug.Log("PrintFloat is called with a value of " + theValue + ":" + Time.time);
    }
}