- Home /
mainTextureOffset not updating via script
Hey Guys, I'm attempting to scroll a texture by updating its .y offset value in script. In the inspector, when I'm not running the script, changing the y value works fine and the texture scrolls as expected.
When I run my script, which simply increments the y value, nothing happens. The .y offset value stays at zero and the texture doesn't move. However...while the script is still running, when I click in the .y field of the offset in the inspector it instantly updates to the correct .y value...but the texture does not move. The texture is set to "Repeat". Its like the .y value is being updated correctly but is not be applied to the material/texture. Any thoughts on what I'm missing? Cheers Touchy
public Vector2 currentOffset;
// Use this for initialization
void Start ()
{
currentOffset = new Vector2(0,0);
}
// Update is called once per frame
void Update ()
{
if(Input.GetKey (KeyCode.U))
{
currentOffset.y += 1;
gameObject.GetComponent<Renderer>().material.mainTextureOffset = currentOffset;
Debug.Log (currentOffset);
}
}
When this first runs, I think it makes a copy of the $$anonymous$$aterial (anything that modifiers $$anonymous$$aterials does that.) So you might be looking at the original $$anonymous$$at, and not the one on your object (should have "(Instance)" added in the Inspector.)
You're also adding 1 to y, which is supposed to do nothing.
Thanks Owen - yep I'm definitely trying to offset the material that is an "instance".
I've jigged around - now when I'm running my script the offset value is now updating in the inspector as expected (not sure what I did to fix that bit...). However, the texture still does not offset to the new value unless I manually change the value in the inspector while the script is running. So yeah, it's like the offset value isn't being applied to this particular instance of the material.
Answer by Statement · Oct 08, 2015 at 07:30 PM
Instead of incrementing it by one (one texture wrap), try incrementing it with Time.deltaTime. Incrementing it with 1 would not make any visible changes since it would perfectly jump to the next repeat.
using UnityEngine;
public class TestUV : MonoBehaviour
{
Vector2 currentOffset;
void Update()
{
if (Input.GetKey(KeyCode.U))
{
currentOffset.y += Time.deltaTime;
gameObject.GetComponent<Renderer>().material.mainTextureOffset = currentOffset;
}
}
}
Works for me. Just remember to press U. The inspector does not update until you click somewhere on the inspector though.
Version 5.2.1f1 (44735ea161b3) Personal
Windows 8
Default material used ("Default-Material")
Ah ha - thanks Statement! (And thanks Owen - I now understand what you meant by "You're also adding 1 to y, which is supposed to do nothing."
I'll give this a crack tonight after the day-job is over.
Yep - that was it...offsetting by 1 was the mistake.
Thanks Statement and Owen!!