Unity3D中播放序列帧动画

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的数量需要自己手动传入,因为无法根据代码动态获取。

posted @ 2013-09-22 16:49  Vital  阅读(5719)  评论(0编辑  收藏  举报