- Home /
Switching Between Textures
Hello. I have got a plane (flat mesh not aircraft) and 10 textures that I want to swap quickly and after all ten start again so I can simulate a waterfall. How can I get all of the textures to cycle one texture every 0.1 of a second and then loop.
Answer by zz74b · May 10, 2012 at 11:42 AM
in c#
private Texture[] _textureArray = Texture[] { texture1, texture2, texture3, ... etc };
void Awake()
{
StartCoroutine(Cycler());
}
IEnumerator Cycler()
{
int currentTex = 0;
while(true)
{
yield return new WaitForSeconds(0.1f);
currentTex++;
var tex = _textureArray[currentTex % _textureArray.Length];
.. Assign texture here.
}
}
Explaination:
Start a co-rountine that loops for ever, waiting 0.1 seconds before it runs each time. Then using modulo maths, selects the next texture from the array of textures. It doesn't matter how many textures you use, it'll always loop correctly.
Assign 'tex' to your plane in the normal way.
[Disclaimer: not tested in unity - may not compile :P]
warning: if you run this code for ages, you may get an integer overflow. I'll leave it up to you to work out how to cope with that situation.
Just add
if(currentTex == _textureArray.Length)
currentTex = 0;
after curentTex++;.
You also don't need modulo maths then.
RE: the integer overflow problem- with normal signed 32-bit integers, you will have to run the program for about SEVENTY YEARS at one increment every 1/10 of a second before that becomes an actual issue. Just saying.
Here I am trying to get newbs to think about the code they are writing and you guys come wading in and giving them all the answers.. :) - What do you think this is? A question and answer site??!
The reason I suggested modulo maths, is in the hope that the OP would go and look up what it is all about and become a better programmer..
Thanks for this. I dont know if this is just a problem with my computer but I found the sprite sheet script on the wiki and that had better performance than this script.