- Home /
Change texture every nth second while key down
I'm trying to figure out how to change the texture of an object every nth second, and while it should be simple, I've had a terrible time trying to figure it out. I'm trying to use an array of textures as a sort of sprite-type animation on a flat plane/quad. I want the texture of that plane to change to the next texture in the array after every nth second while the player is holding down a key. Any help would be greatly appreciated. I'm trying to figure it out in C#.
Answer by whydoidoit · Aug 11, 2013 at 08:00 AM
You should start a coroutine when the button is pressed and have it verify the key is down, then do the wait. It could be written as a generic coroutine to work on anything as shown here:
public Texture2D[] textures;
void Update()
{
if(Input.GetKeyDown(KeyCode.Y))
{
StartCoroutine(ChangeTextures(renderer, textures, KeyCode.Y, 1));
}
}
//This will change anything and so could be in a Utility class
public static IEnumerator ChangeTextures(Renderer renderer, Texture2D[] textures, KeyCode code, float delay)
{
var textureToUse = 0;
while(Input.GetKey(code))
{
renderer.material.mainTexture = textures[textureToUse];
textureToUse++;
if(textureToUse >= textures.Length) textureToUse = 0;
yield return new WaitForSeconds(delay);
}
}
Thank you for the extremely quick answer! I had actually tried this earlier, and while it does work, I seem to be having a problem with this still in that while the key is down, because it is being called in Update, it calls the coroutine for however many frames the key is down. This makes the textures just flash on the object extremely fast several times over.
In your Update's if, add a
debug.Log("$$anonymous$$eydown detected");
to check if it is really called that often. But it shouldn't, Get$$anonymous$$eyDown only returns true, on the frame the key was pressed down, otherwise it is false;
Hmm... I guess that isn't it. However, I continue to have that same problem where all textures in the array flash across the plane, waits the delay, then flashes the textures again. Any ideas?
Would it be possible you're launching several coroutines and that they are running simultaniously?
If you have a similar code to what whydoidoit wrote, your key's state is only checked once every second. if you released the key and pressed it again in between two checks... your first coroutine would still be running, and you would have launched a second one.
That's a very good point. You could probably use a loop to check for the elapsed time and also the key release.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to use Multi-Tap in New Input System for Running? 1 Answer
(C#) A better way to limit actions to once per button press? 2 Answers
Double tap mechanics and axis inputs 3 Answers