Unity流水賬5:Animation Events
阿新 • • 發佈:2018-12-09
你可以通過使用Animation Events來增加Animation Clips的有用性,它允許你在時間軸中指定的點呼叫物件指令碼中的函式。 Animation Event呼叫的函式還可以選擇接受一個引數。引數可以是浮點數、字串、int或物件引用,也可以是Animation Event物件。AnimationEvent物件有成員變數,他們允許一個浮點數、字串、整數和物件引用同時被傳遞到函式中,以及觸發函式呼叫的事件的其他資訊。 若要在當前播放頭位置向clip新增動畫事件,請單擊事件按鈕。將對話時間新增到動畫中的任意點。在希望觸發事件的點雙擊事件行。新增後,可以拖動滑鼠重新定位事件。要刪除事件,請選擇它並按下delete鍵,或右鍵單擊它並選擇delete event;
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座標的位置曲線。 接下來,將x座標的動畫設定為大約0.4,然後在一秒內回到0,然後大約在0.8秒內建立一個動畫事件。按下Play以執行動畫。
程式碼示例:
using UnityEngine;
public class AnimationEventTest:MonoBehaviour
{
public void PrintFloat(float theValue)
{
Debug.Log("PrintFloat is called with a value of " + theValue + ":" + Time.time);
}
}
動態新增動畫事件:
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);
}
}