產品中經常用到加載動圖,一般情況呢,我們都會根據UI設計師所給的UI圖進行製作,我這裏就介紹兩種做法,此篇博客只是記錄我怎麼做的,方便我後續用,也希望能幫到大家。
第一種是讓UI設計師給一張包含裏所有序列幀的大圖
比如:
導入到Unity中選中
再將Sprite Mode設置改成Multiple,打開Sprite Editor進行編輯
第二種是UI設計師把所有序列幀的圖都給過來直接用代碼實現加載
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Image))]
public class Loading : MonoBehaviour
{
[Tooltip("sprite")]
public List<Sprite> sprite_frame;
[Tooltip("幀動畫播放的時間間隔")]
public float duration = 0.1f;
[Tooltip("循環")]
public bool loop = false;
[Tooltip("是否在加載中播放")]
public bool loadplay = false;
[Tooltip("播放完是否銷燬")]
public bool destroy = true;
[Tooltip("延遲多少秒播放")]
public float timeDelay = 0;
[Tooltip("如果重複播放多少秒後播放")]
public float playTimeEndDelay = 0;
private float played_time;
private bool playing = false;
private Image img;
private bool currentDelay = false;
private bool currentPlayDelay = false;
// Start is called before the first frame update
void Start()
{
this.img = this.GetComponent<Image>();
if (this.loadplay)
{
this.Play();
}
}
public void Play()
{
if (this.loop)
{
this.Play_loop();
}
else
{
this.Play_once();
}
}
public void Stop()
{
this.playing = false;
}
void Play_once()
{
if (this.sprite_frame.Count <= 1)
{
return;
}
if (timeDelay > 0)
{
currentDelay = true;
Invoke("UpdataTimeDelayState", this.timeDelay);
}
this.played_time = 0;
this.playing = true;
this.loop = false;
}
void Play_loop()
{
if (this.sprite_frame.Count <= 1)
{
return;
}
if (timeDelay > 0)
{
currentDelay = true;
Invoke("UpdataTimeDelayState", this.timeDelay);
}
this.played_time = 0;
this.playing = true;
this.loop = true;
}
private void UpdataTimeDelayState()
{
currentDelay = false;
}
private void UpdataPlayTimeDelayState()
{
currentPlayDelay = false;
}
// Update is called once per frame
void Update()
{
if (!this.playing)
{
return;
}
if (currentDelay || currentPlayDelay)
{
return;
}
float dt = Time.deltaTime;
this.played_time += dt;
int index = (int)(this.played_time / this.duration);
if (!this.loop)
{
if (index >= this.sprite_frame.Count)
{
this.playing = false;
this.played_time = 0;
if (destroy)
{
Destroy(this.gameObject);
}
}
else
{
this.img.sprite = this.sprite_frame[index];
}
}
else
{
while (index >= this.sprite_frame.Count)
{
this.played_time -= (this.duration * this.sprite_frame.Count);
index -= this.sprite_frame.Count;
currentPlayDelay = true;
Invoke("UpdataPlayTimeDelayState", this.playTimeEndDelay);
}
this.img.sprite = this.sprite_frame[index];
}
}
}