In Unity3d, when an object has a material applied to it, if you change the scale of that object, the material keeps the 1:1 scale on the object.
One of the prototypes that i was working need to have objects of different sizes showing the same texture, but having the texture showing the same resolution. So to save having to make 10+ different sizes of the same image, i had a look to see if i could make a little code to solve this.
I had a look on Unity answers (http://answers.unity3d.com) to see if any one had come up with a solution to the problem. i found one post on the subject, they suggested:
renderer.material.mainTextureScale = Vector2 (#,#);
This put me on the right track. However, unity works from the bottom left, so when i scaled the texture, it scaled it from this point rather than the center.
After a little more digging on Unity Answers, i found another post about a different problem and they suggested:
renderer.material.mainTextureOffset = Vector2 (#,#);
Now i just need to work out a algorithm for how much the texture need to be off set depending on the objects scale and the material scale.
Ill skip all the trial and error part and explain the end result:
private var TexScale:float;
private var TexOffSetPrem:float;
private var TexOffSet:float;
function Start ()
{
TexScale = transform.localScale.x;
TexOffSetPrem = (transform.localScale.x - 1) * -10;
TexOffSet = (Mathf.Round(TexOffSetPrem * 5)) /100;
renderer.material.mainTextureScale = Vector2 (TexScale,TexScale);
renderer.material.mainTextureOffset = Vector2 (TexOffSet,TexOffSet);
}
To begin with, 'TexScale' looks at the object's scale and adjusts the scale of the texture accordingly. Beacuse X scale and Y scale are the same, there was no need to look at both.
Next, to make things easy, i stated that when the object had a scale of 1, the material also had a scale of one. After that, i then worked out that for every +/- 0.1 that the scale differed, the material's offset needed to be adjusted by +/- 0.5 respectively.
There was some issues with multiplying decimals, so i converted it into whole numbers then back to decimals to be used in the off set function.
This little bit of code gave me the desired result.


No comments:
Post a Comment