forked from RonenNess/UnityUtils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecalcTextureTile.cs
More file actions
79 lines (69 loc) · 2.6 KB
/
RecalcTextureTile.cs
File metadata and controls
79 lines (69 loc) · 2.6 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Recalculate texture tiling to always tile the texture at the same desired size.
* This means that if you have bricks texture, for example, you can tile it evenly on all surfaces, no matter their size.
* Code is based on answer from here and heavily modified:
* https://gamedev.stackexchange.com/questions/111060/unity-tiling-of-a-material-independen-of-its-size
*
* Note: this will update material in editor itself.
*
* Author: Ronen Ness.
* Since: 2018.
*/
using UnityEngine;
namespace NesScripts.Graphics
{
[ExecuteInEditMode]
public class RecalcTextureTile : MonoBehaviour
{
/// <summary>
/// Texture scale factor.
/// </summary>
public float ScaleFactor = 5.0f;
/// <summary>
/// Desired size of a single texture tile, in pixels.
/// Set to 0,0 to take full texture size.
/// </summary>
public Vector2 DesiredTileSizeInPixels = new Vector2(0, 0);
/// <summary>
/// If true (default) will use Z axis for y.
/// </summary>
public bool UseAxisZ = true;
/// <summary>
/// Set this to true to make the object update once (it turns false immediately).
/// </summary>
public bool ForceUpdateNow = true;
// Update is called once per frame
void Update()
{
// update material for when we're in editor mode
if ((transform.hasChanged || ForceUpdateNow) &&
(Application.isEditor && !Application.isPlaying))
{
// update texture
UpdateTextureScale();
// set no changes and update last scale param
transform.hasChanged = false;
ForceUpdateNow = false;
}
}
/// <summary>
/// Recalc and update texture scale.
/// </summary>
void UpdateTextureScale()
{
// get desired texture size in pixels
var desiredTextSize = DesiredTileSizeInPixels;
// set default desired tile size
if (desiredTextSize.magnitude == 0)
{
var text = GetComponent<Renderer>().sharedMaterial.mainTexture;
desiredTextSize.x = text.width;
desiredTextSize.y = text.height;
}
// calc texture tile
GetComponent<Renderer>().sharedMaterial.mainTextureScale = new Vector2(
(transform.lossyScale.x / desiredTextSize.x) / ScaleFactor,
((UseAxisZ ? transform.lossyScale.z : transform.lossyScale.y) / desiredTextSize.y) / ScaleFactor);
}
}
}