旧的方法
直接在update中每帧切换图片资源的话,动画显示会很硬直。
实现效果
资源处理
- 将8*4的png图片导入到工程中,Texture Type设置为Editor GUI and Legacy GUI或者Sprite。
- 新建一个材质球,Shader设置为Legacy Shaders/Particles/Additive或者Mobile/Particles/Additive
UI组件
- Cavnas下新建一个Image组件
- 将目标Image组件的Material改为新建的材质
组件代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LoopTings : MonoBehaviour
{
Image _img;
Material _material;
float startTime;
[Header("X轴图片数量")]
public int countX = 8;
[Header("Y轴图片数量")]
public int countY = 8;
public float _speed = 26f;
#if UNITY_EDITOR
private void OnValidate()
{
_material = transform.GetComponent<Image>().material;
// 设置平铺和偏移
Vector2 inital = new Vector2((1f / countX), (1f / countY));
_material.mainTextureScale = inital;
_material.mainTextureOffset = inital;
}
#endif
// Start is called before the first frame update
void Start()
{
_img = transform.GetComponent<Image>();
_material = _img.material;
startTime = Time.time;
}
// Update is called once per frame
void Update()
{
updateOffset();
}
void updateOffset()
{
float index = (Time.time - startTime) * _speed;
if ((index <= (countX * countY)))
{
index = index % (countX * countY);
Debug.Log(">>" + index);
if (index == (countX * countY))
{
startTime = Time.time;
index = 0;
}
// 小图尺寸
Vector2 size = new Vector2(1.0f / countX, 1.0f / countY);
// 计算索引
float uIndex = Mathf.Floor(index % countX);
float vIndex = Mathf.Floor(index / countX);
// 计算偏移值
Vector2 offset = new Vector2(uIndex * size.x, 1.0f - size.y - vIndex * size.y);
// 设置偏移
_material.SetTextureOffset("_MainTex", offset);
}
else
{
// 重置
startTime = Time.time;
}
}
}
设置组件
将代码丢给目标Image,根据图片大小设置对应数值。
因为图片是8*4个小图组成。所以X轴数量设8,Y轴数量设4。同样适用于3x3或者8x8的图。
速度自己改下就知道效果啦。