首頁 > 軟體

Unity UI實現迴圈播放序列圖

2021-08-08 13:00:08

一、思路

1.獲取播放元件

一般我們使用UI的Raw Image或者Image來顯示圖片

Image:僅支援Sprite型別圖片,需要更改圖片的格式(注意:在StreamingAssets資料夾裡的圖片是更改不了型別的,在這裡必須放在Assets/Resources路徑下

Raw Image:支援圖片的原格式,一般我們將其轉換成 Texture2D使用

2.載入圖片

Resources提供了一個Load方法,可以從Resources資料夾裡載入圖片。

!!!!!注意一定要在Resources路徑下,否則找不到

Resources.Load(path, typeof(Texture2D)) as Texture2D;
Resources.Load(path, typeof(Sprite)) as Sprite;

3.迴圈載入

記錄當前到哪一張,判斷是不是到了最後一張,是,載入第一張

二、範例程式碼

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
 
public class FramesController : MonoBehaviour
{
    [System.Serializable]
    public struct NameRules
    {
        [Header("基礎名稱(基礎名字就是序列圖名稱中絕對相同的)")]
        public string BaseName;
 
        [Header("有效數位的位數(代表排序的有效數位位數)")]
        public int SignificantDigits;
 
        [Header("開始數(開始的數)")]
        public int Start;
 
        [Header("總數(一共多少張圖片)")]
        public int Count;
 
        public NameRules(string _name,int _digits,int _start,int _count)
        {
            BaseName = _name;
            SignificantDigits = _digits;
            Start = _start;
            Count = _count;
        }
    }
    //圖片型別
    public enum WidgetType
    {
        Image,
        RawImage
    }
    /// 
    [Header("圖片顯示控制元件(RawImage[支援原始圖片型別] OR Image[僅支援Sprite圖片])")]
    public WidgetType ImgWidget = WidgetType.RawImage;
 
    //要求資料夾必須在Assets/Resources資料夾裡面,ModeName填寫後面到資料夾的路徑
    [Header("模式名稱(和資料夾名稱相同,路徑必須在Resources裡面)")]
    public string ModeName = "請填寫資料夾路徑";
 
    [Header("命名規則(序列圖的命名規則)")]
    public NameRules Rules;
 
    [Header("FPS(一秒內顯示多少張圖片)")]
    public int FramesPerSecond = 24;
 
    [Header("迴圈播放(預設開啟)")]
    public bool Loop=true;
 
    [Header("UI可用時自動播放(預設開啟)")]
    public bool PlayOnWake=true;
 
 
 
 
    /// <summary>
    /// 私有變數
    /// </summary>
    /// /// 顯示圖片的UI控制元件
    private Image ImageComponent = null;
    private RawImage RawImgComponent = null;
 
    
    private int currentFrames;//當前播放的圖片幀數
    private float showTime = 0.0f;
    private float rateTime = 0.0f;
 
    private bool Playing;
 
    // Start is called before the first frame update
    void Start()
    {
        InitWidget();
    }
    // Update is called once per frame
    void Update()
    {
        if (!Playing) return;
        showTime += Time.deltaTime;
        if (showTime >= rateTime)
        {
            showTime = 0;
            currentFrames++;
            if (currentFrames >= Rules.Count)
            {
                if(Loop)
                {
                    currentFrames = Rules.Start;
                }else
                {
                    Playing = false;
                }
            }
            if(ImgWidget == WidgetType.Image)
            {
                ImageComponent.sprite = GetCurrentSprite();
            }
            else
            {
                RawImgComponent.texture = GetCurrentTexture2D();
            }
        }
    }
 
    /// /更換播放的序列圖
    public void ChangeMode(string _mode, NameRules _rules, int _fps=24)
    {
        ModeName = _mode;
        Rules=_rules;
        FramesPerSecond = _fps;
 
        currentFrames = Rules.Start;
        rateTime = 1.0f / FramesPerSecond;
        if (ImgWidget == WidgetType.Image)
        {
            ImageComponent.sprite = GetCurrentSprite();
        }
        else
        {
            RawImgComponent.texture = GetCurrentTexture2D();
        }
    }
    //開始播放
    public void Play(bool needLoop=true)
    {
        Playing = true;
        Loop = needLoop;
    }
    //停止播放
    public void Stop()
    {
        Playing = false;
    }
 
    private Sprite GetCurrentSprite()
    {
        /這個是重點,顯示不出來圖片的話,大概率問題在這個函數
        string formatStr = "{0:D" + Rules.SignificantDigits + "}";//保留有效數位,不夠前面加0
        string imageName = ModeName + "/" + Rules.BaseName + string.Format(formatStr, currentFrames);
        return LoadSprite(imageName);
    }
 
    private Texture2D GetCurrentTexture2D()
    {
        /這個是重點,顯示不出來圖片的話,大概率問題在這個函數
        string formatStr = "{0:D"+ Rules .SignificantDigits+ "}";//保留有效數位,不夠前面加0
        string imageName = ModeName+"/"+Rules.BaseName + string.Format(formatStr, currentFrames);
        return LoadTexture2D(imageName);
    }
 
    private Texture2D LoadTexture2D(string path)
    {
        return Resources.Load(path, typeof(Texture2D)) as Texture2D;
    }
 
    private Sprite LoadSprite(string path)
    {
        return Resources.Load(path, typeof(Sprite)) as Sprite;
    }
    /// <summary>
    /// 初始化圖片顯示元件
    /// </summary>
    private void InitWidget()
    {
        if(ImgWidget== WidgetType.Image)
        {
            ImageComponent = transform.gameObject.GetComponent<Image>();
            if(ImageComponent==null)
            {
                EditorBox("此元件上沒有找到<Image>!請檢查後重試!");
                EditorStop();
            }
        }
        else
        {
            RawImgComponent = transform.gameObject.GetComponent<RawImage>();
            if (RawImgComponent == null)
            {
                EditorBox("此元件上沒有找到<RawImage>!請檢查後重試!");
                EditorStop();
            }
        }
        Playing = PlayOnWake;
        currentFrames = Rules.Start;
        rateTime = 1.0f / FramesPerSecond;
        if (ImgWidget == WidgetType.Image)
        {
            ImageComponent.sprite = GetCurrentSprite();
        }
        else
        {
            RawImgComponent.texture = GetCurrentTexture2D();
        }
    }
 
    /// <summary>
    /// Unity編輯器的MessageBox
    /// </summary>
    private void EditorBox(string msg)
    {
#if UNITY_EDITOR
        EditorUtility.DisplayDialog("FramesController", msg, "確認", "取消");
#endif
    }
    /// <summary>
    /// Unity編輯器停止當前正在執行的程式
    /// </summary>
    private void EditorStop()
    {
#if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
#endif
    }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com