写在前面:
2DSprite图片的帧动画,直接选中Assets里所有素材图片,往它身上一拖,就会自动生成(2DSprite创建:右键——>2D Object——>Sprite)。
其缺点是如果UGUI中Canvas的渲染模式RenderMode是ScreenSpace——Overlay,2DSprite的帧动画,会被UGUI的图片遮住,所以UGUI的Image图片帧动画不能如此操作——可以用脚本来实现——NGUI的Sprite图片帧动画脚本与之类似。
UGUI Image图片 帧动画
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScriptPlayAnim : MonoBehaviour
{
public bool ActivateWait = false;
float fireRate = 0.2f;
int i = 0;
float nextFire;
public Sprite[] ActivatorTexture = new Sprite[] { };
// Use this for initialization
void Start ()
{
this.GetComponent<Image>().enabled = false;
}
// Update is called once per frame
void Update ()
{
if (ActivateWait)
{
this.GetComponent<Image>().enabled = true;
if (i < ActivatorTexture.Length)
{
if (Time.time > nextFire)
{
nextFire = Time.time + fireRate;
this.GetComponent<Image>().sprite = ActivatorTexture[i];
i++;
}
}
else
{
i = 0;
}
}
else
{
this.GetComponent<Image>().enabled = false;
}
}
}
素材图片,挨个儿拖入数组
在Inspector面板里,勾选bool变量ActivatorWait后,图片显现,并循环播放
NGUI Sprite图片 帧动画
与以上类似,不同之处是切换图片的方式:
UGUI Image图片为 this.GetComponent().sprite = ActivatorTexture[i];
NGUI Sprite图片为 this.GetComponent().spriteName = ActivatorTexture[i];(NGUI里的图片是打成图集是用的,得把图片的的名字存放在 ActivatorTexture[]数组中,通过切换名字来切换图片)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScriptPlayNGUIAnimation : MonoBehaviour {
public bool ActivateWait = false;
float fireRate = 0.2f;
int i = 0;
float nextFire;
string[] ActivatorTexture = new string[] { "1", "2", "3", "4", "5", "6", "7" }; //这里存放我们需要调用的序列帧的名称,这种方法比较笨拙,
//只适合使用图片较少的情况,当图片很多的情况下,我们可以使用代码控制名称,思路是前面的名称一样,后面的名称代表序列帧编号,我们只要
//在代码中根据编号加上前缀名称就可以得到所需序列帧的全名。具体使用参见下面的Texture序列帧动画。
void Awake()
{
this.GetComponent<UISprite>().enabled = false;
}
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
if (ActivateWait)
{
this.GetComponent<UISprite>().enabled = true;
if (i < ActivatorTexture.Length)
{
if (Time.time > nextFire)
{
nextFire = Time.time + fireRate;
this.GetComponent<UISprite>().spriteName = ActivatorTexture[i];
i++;
}
}
else
{
i = 0;
}
}
else
{
this.GetComponent<UISprite>().enabled = false;
}
}
}
像UGUI方式一样:在Inspector面板里,勾选bool变量ActivatorWait后,图片显现,并循环播放。只是,数组已手动定义好,不必往里拖了。
核心思路
每隔固定时间(此处是fireRate)给图片换一张图像