Unity Animation 之 三種方法暫停繼續播放動畫

來源:酷知科普網 2.39W

Unity Animation 之 三種方法暫停、繼續在播放動畫。在Unity中,暫停是遊戲玩家會用到的遊戲功能。本節介紹使用三種方式暫停Animation正在播放的動畫隨後繼續播放的簡單案例,具體如下

一、知識要點

(01)Animation:class in UnityEngineThe animation component is used to play back animations.You can assign animation clips to the animation component and control playback from your script. The animation system in Unity is weight-based and supports Animation Blending, Additive animations, Animation Mixing, Layers and full control over all aspects of playback.

(02)方法提要:1)方法一timeRecd = anim ["Run"].time;anim.Stop ()anim ["Run"].time = timeRecd;anim.Play ("Run");2)方法二anim ["Run"].speed = 0;anim ["Run"].speed = 1;3)方法三Time.timeScale = 0Time.timeScale = 1;

二、Animation 之 三種方法暫停正在播放動畫

(01)開啟Unity,新建一個空工程,具體如下

Unity Animation 之 三種方法暫停繼續播放動畫

(02)匯入一個帶動畫的遊戲模型,並把遊戲模型拖到場景中,並新增動畫,具體如下圖

Unity Animation 之 三種方法暫停繼續播放動畫 第2張

(03)新建一個指令碼“AnimationTest”,雙擊指令碼或者右鍵“Open C# Project”開啟指令碼,具體如下圖

Unity Animation 之 三種方法暫停繼續播放動畫 第3張

(04)在開啟的“AnimationTest”指令碼上編寫程式碼,首先設定來哥哥變數,一個獲得“Animation”元件,一個記錄時間,然後設定按下“R”把動畫切換到跑的狀態,接著三種方法實現動畫暫停,程式碼及程式碼說明如下圖

Unity Animation 之 三種方法暫停繼續播放動畫 第4張

(05)“AnimationTest”指令碼具體了內容如下:using UnityEngine;public class AnimationTest : MonoBehaviour {public Animation anim;private float timeRecd;// Update is called once per framevoid Update () {if (Input.GetKeyDown (KeyCode.R)) {anim.Play ("Run");}#region  方法一if (Input.GetKeyDown (KeyCode.S)) {timeRecd = anim ["Run"].time;anim.Stop ();}if (Input.GetKeyDown (KeyCode.C)) {anim ["Run"].time = timeRecd;anim.Play ("Run");}#endregion#region  方法二if (Input.GetKeyDown (KeyCode.D)) {anim ["Run"].speed = 0;}if (Input.GetKeyDown (KeyCode.F)) {anim ["Run"].speed = 1;}#endregion#region  方法三if (Input.GetKeyDown (KeyCode.A)) {Time.timeScale = 0;}if (Input.GetKeyDown (KeyCode.B)) {Time.timeScale = 1;}#endregion}}

(06)指令碼編譯正確,回到Unity介面,在場景中新建一個“GameObject”,把指令碼“AnimationTest”賦給“GameObject”,並把模型的“Animation”賦給指令碼,具體如下圖

Unity Animation 之 三種方法暫停繼續播放動畫 第5張

(07)執行場景,通過不同的三種方法,實現了動畫的暫停播放,具體如下圖

Unity Animation 之 三種方法暫停繼續播放動畫 第6張

(08)到此,《Unity Animation 之 三種方法暫停正在播放動畫》講解結束,謝謝

熱門標籤