ScrollDetailTexture.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. [RequireComponent(typeof(Image))]
  4. public class ScrollDetailTexture : MonoBehaviour
  5. {
  6. public bool uniqueMaterial = false;
  7. public Vector2 scrollPerSecond = Vector2.zero;
  8. Matrix4x4 m_Matrix;
  9. Material mCopy;
  10. Material mOriginal;
  11. Image mSprite;
  12. Material m_Mat;
  13. void OnEnable ()
  14. {
  15. mSprite = GetComponent<Image>();
  16. mOriginal = mSprite.material;
  17. if (uniqueMaterial && mSprite.material != null)
  18. {
  19. mCopy = new Material(mOriginal);
  20. mCopy.name = "Copy of " + mOriginal.name;
  21. mCopy.hideFlags = HideFlags.DontSave;
  22. mSprite.material = mCopy;
  23. }
  24. }
  25. void OnDisable ()
  26. {
  27. if (mCopy != null)
  28. {
  29. mSprite.material = mOriginal;
  30. if (Application.isEditor)
  31. UnityEngine.Object.DestroyImmediate(mCopy);
  32. else
  33. UnityEngine.Object.Destroy(mCopy);
  34. mCopy = null;
  35. }
  36. mOriginal = null;
  37. }
  38. void Update ()
  39. {
  40. Material mat = (mCopy != null) ? mCopy : mOriginal;
  41. if (mat != null)
  42. {
  43. Texture tex = mat.GetTexture("_DetailTex");
  44. if (tex != null)
  45. {
  46. mat.SetTextureOffset("_DetailTex", scrollPerSecond * Time.time);
  47. // TODO: It would be better to add support for MaterialBlocks on UIRenderer,
  48. // because currently only one Update() function's matrix can be active at a time.
  49. // With material block properties, the batching would be correctly broken up instead,
  50. // and would work with multiple widgets using this detail shader.
  51. }
  52. }
  53. }
  54. }