summaryrefslogtreecommitdiff
path: root/Assets/SampleUI/Scripts/ScrollDetailTexture.cs
blob: 305383b4916897983d11a057e2e2fec08e2dfaf7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using UnityEngine;
using UnityEngine.UI;


[RequireComponent(typeof(Image))]
public class ScrollDetailTexture : MonoBehaviour
{
	public bool uniqueMaterial = false;
	public Vector2 scrollPerSecond = Vector2.zero;

	Matrix4x4 m_Matrix;
	Material mCopy;
	Material mOriginal;
	Image mSprite;
	Material m_Mat;

	void OnEnable ()
	{
		mSprite = GetComponent<Image>();
		mOriginal = mSprite.material;

		if (uniqueMaterial && mSprite.material != null)
		{
			mCopy = new Material(mOriginal);
			mCopy.name = "Copy of " + mOriginal.name;
			mCopy.hideFlags = HideFlags.DontSave;
			mSprite.material = mCopy;
		}
	}

	void OnDisable ()
	{
		if (mCopy != null)
		{
			mSprite.material = mOriginal;
			if (Application.isEditor)
				UnityEngine.Object.DestroyImmediate(mCopy);
			else
				UnityEngine.Object.Destroy(mCopy);
			mCopy = null;
		}
		mOriginal = null;
	}

	void Update ()
	{
		Material mat = (mCopy != null) ? mCopy : mOriginal;

		if (mat != null)
		{
			Texture tex = mat.GetTexture("_DetailTex");

			if (tex != null)
			{
				mat.SetTextureOffset("_DetailTex", scrollPerSecond * Time.time);

				// TODO: It would be better to add support for MaterialBlocks on UIRenderer,
				// because currently only one Update() function's matrix can be active at a time.
				// With material block properties, the batching would be correctly broken up instead,
				// and would work with multiple widgets using this detail shader.
			}
		}
	}
}