using UnityEngine; using System.Collections; public class UVAnimCtrl : MonoBehaviour { public bool loop=true; public float scrollSpeed = 5; public float countX = 4; public float countY = 4; private float offsetX = 0.0f; private float offsetY = 0.0f; private Vector2 singleTextureSize; private float _frame = 0.0f; private float stepx; private float stepy; public bool isOffset = false; public float ox = 0.0f; public float oy = 0.0f; private bool _isEnable = true; public bool isEnable { get { return _isEnable; } set { _isEnable = value; if (value) enabled = true; } } void Awake() { singleTextureSize = new Vector2(1.0f / countX, 1.0f / countY); GetComponent().material.mainTextureScale = singleTextureSize; foreach (Material i in GetComponent().materials) { i.mainTextureScale = singleTextureSize; } } /// /// Update用于普通更新的情况,与enable和isEnable搭配使用;与UpdateFrame互斥 /// void Update() { if (_isEnable) _OnUpdate(); else this.enabled = false; } public void UpdateFrame() { _OnUpdate(); } private void _OnUpdate() { if(isOffset) { if(loop) { if(offsetX <-1) offsetX +=1; if(offsetY < -1) offsetY +=1; if(offsetX >1) offsetX -=1; if(offsetY >1) offsetY -=1; } else { if(offsetX <-1) return; if(offsetY < -1) return; if(offsetX >1) return; if(offsetY >1) return; } offsetX += ox; offsetY += oy; } else { if (stepy >=countY){ if(loop){ stepy = 0f; } else { return; } } _frame += Time.deltaTime; stepx = Mathf.Floor(_frame * scrollSpeed); offsetX = stepx / countX; if (stepx >= countX) { stepy+=1; _frame = 0; } offsetY = stepy / countY; //offsetY = -(_frame - _frame % countX) / countY / countX; } foreach (Material i in GetComponent().materials) { i.SetTextureOffset("_MainTex", new Vector2(offsetX, offsetY)); } } }