标签:sprite mono unity3d image 行编辑 upd tooltip ui设计 png
产品中经常用到加载动图,一般情况呢,我们都会根据UI设计师所给的UI图进行制作,我这里就介绍两种做法,此篇博客只是记录我怎么做的,方便我后续用,也希望能帮到大家。第二种是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];
}
}
}
标签:sprite mono unity3d image 行编辑 upd tooltip ui设计 png
原文地址:https://blog.51cto.com/myselfdream/2489042