古いやり方
更新時に画像リソースをフレームごとに直接切り替えると、アニメーション表示が非常に硬くなります。
効果を達成する
リソースの処理
- 8*4 PNG イメージをプロジェクトにインポートし、テクスチャ タイプをEditor GUI および Legacy GUIまたはSpriteに設定します。
- 新しいシェーダ ボールを作成し、シェーダをLegacy Shaders/Particles/AdditiveまたはMobile/Particles/Additiveに設定します。
UIコンポーネント
- Cavnas の下に新しい Image コンポーネントを作成します
- 対象の画像コンポーネントのマテリアルを新しいマテリアルに変更します
コンポーネントコード
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;
}
}
}
セットアップコンポーネント
ターゲットの画像にコードをスローし、画像のサイズに応じて対応する値を設定します。
なぜなら、絵は8*4枚の小さな絵で構成されているからです。したがって、X 軸の数量は 8 に設定され、Y 軸の数量は 4 に設定されます。3x3 または 8x8 画像にも同じことが当てはまります。
自分で速度を変更するだけで効果がわかります。