class FrameAnimation { private float fps = 10.0f; private Rect drawPos; private float time = 0; private int currentIndex = 0; public void DrawFrameAnimation(Texture[] frameTex) { int length = frameTex.Length; GUI.DrawTexture(drawPos, frameTex[currentIndex]); time += Time.deltaTime; if(time >= 1.0f/fps) { currentIndex++; time = 0; if(currentIndex>= length-1) { currentIndex = length - 1; } } } public FrameAnimation(Rect drawPos,float fps) { this.drawPos = drawPos; this.fps = fps; } }
在unity3D中新建一個腳本直接調用該類。
using UnityEngine; using System.Collections; public class DrawAnimation : MonoBehaviour { //private Resources resource; private Rect drawPos = new Rect(200,0,500,200); private Object[] texObject; public bool isCanDraw = false; private string path; Texture[] frameTex; private FrameAnimation frameAni; // Use this for initialization void Start () { LoadTexture(texObject,"FrameTex"); frameAni = new FrameAnimation( drawPos, 10); } void OnGUI() { if(GUILayout.Button("@#@")) { isCanDraw = true; } if(isCanDraw) { frameAni.DrawFrameAnimation(frameTex); } } void LoadTexture(Object[] texObj, string path) { texObj = Resources.LoadAll(path); frameTex = new Texture[texObj.Length]; texObj.CopyTo(frameTex, 0); } }
其實完全沒有必要寫成類,但是為了方便修改和最近在練習寫代碼的習慣,希望逐漸面向對象編程,希望可以提高代碼的靈活性和復用性,所以就當是練習了!
2013/9/26:
發現把所有圖片一次性全部導入,加載相當的消耗資源,在PC上都會卡上一下,何況在移動平台上,特別有的時候圖片稍微多的時候。
所以把代碼稍作修改:
int currentIndex = 0; Texture frameAniTex; // Use this for initialization void Start () { } // Update is called once per frame void FrameAnimation() { //isAnimating = true; frameAniTex = resources.GetTexture("BootAnim/" + currentIndex.ToString("D4")); GUI.DrawTexture(frameAnimPos,frameAniTex); if (currentIndex < length - 1) { time += Time.deltaTime; if (time >= 1.0f / fps) { currentIndex++; time = 0; if (currentIndex == length - 1) { Resources.UnloadUnusedAssets(); ///加載完成后,即播放完畢后,卸載掉這些資源,好像跟播放序列幀動畫扯遠了,這是加載資源管理才對、、、、、 } } } }
這樣做的好處是一張一張的加載資源,不像上面的那樣一次性加載完,但是圖片的數量即length的數量需要自己手動傳入,因為無法根據代碼動態獲取。