unity 動畫控制


播放控制

Animator animator;

animator.speed=0;//停止播放
animator.speed=-1;//倒放

animator.Play("stateName",0,0);//播放指定狀態(stateName是Animator窗口里各個狀態的名稱)

跳到指定幀,並停止

Animator animator;

animator.speed=0;//停止播放

AnimationClip clip=animator.runtimeAnimatorController.animationClips[0];
float frameTime=(1f/clip.frameRate)*5;//跳到第5幀

animator.Play("stateName",0,frameTime);//播放指定狀態(stateName是Animator窗口里各個狀態的名稱)

在動畫指定的時間里,添加事件函數
注意:函數所在的腳本和Animator 組件必須綁定到同一個GameObject

using UnityEngine;
using System.Collections;

public class TestAnimationEvent:MonoBehaviour{
	
	private void Awake(){
		Animator animator=GetComponent<Animator>();//Animator組件和此腳本必須綁定到同一個GameObject
                
		AnimatorOverrideController overrideController=new AnimatorOverrideController(animator.runtimeAnimatorController);
		//通過子符串獲取AnimationClip,注意並不是Animator窗口里各個狀態的名稱,而是在Animator窗口中選擇的狀態在Inspector面板的motion屬性顯示的名稱
		AnimationClip clip=overrideController["CINEMA_4D___"];

		//在動畫指定的時間,添加事件
		AnimationEvent onCompleteEvent=new AnimationEvent();
		onCompleteEvent.objectReferenceParameter=this;
		onCompleteEvent.functionName=nameof(OnAnimationClipComplete);
		onCompleteEvent.time=clip.length;//clip.length動畫長度,單位為秒。這里表示在結束時添加事件
		clip.AddEvent(onCompleteEvent);
	}

	private void OnAnimationClipComplete(UnityEngine.Object objectReference){//注意:參數類型是UnityEngine.Object不是object
		//注意:當內存中擁有多個當前類的實例時,將會調用多次此函數,使用objectReferenceParameter屬性傳遞this區分
		if(objectReference!=this)return;

		Debug.Log("onShakeAnimComplete;");
	}
}

第二種方法:
通過AnimatorStateInfo.normalizedTime判斷播放完成

using UnityEngine;
using System.Collections;

public class Test:MonoBehaviour{

	public Animator animator;

	private void Awake(){
		animator.Play("attack");
		InvokeRepeating(nameof(checkStateComplete),0.02f,0.02f);
	}

	private void checkStateComplete(){
		AnimatorStateInfo stateInfo=animator.GetCurrentAnimatorStateInfo(0);
		if(stateInfo.IsName("attack")){
            //normalizedTime:表示動畫的標准化時間,區間:[0,1]
			if(stateInfo.normalizedTime>=1.0f) {
				onStateComplete();
				CancelInvoke(nameof(checkStateComplete));
			}
		}
	}
	
	private void onStateComplete(){
		Debug.Log("onStateComplete");
	}
	
	private void OnDestroy(){
		CancelInvoke("checkStateComplete");
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM