I have a sphere and would like the sphere to have an animated water texture. I’m trying to swap out the textures using an array. What am I doing wrong?
using UnityEngine;
using System.Collections;
public class animateTexture : MonoBehaviour
{
public Texture[] water;
void Update ()
{
for (int i = 0; i < water.Length; i++)
{
StartCoroutine(MyMethod());
renderer.material.mainTexture = water*;*
_ Debug.Log(water*);_
_ }*_
* }*
IEnumerator MyMethod()
* {*
* yield return new WaitForSeconds(1);*
* }*
}
Any advice would be much appreciated.
Try something like this:
public class TextureSwitcher : MonoBehaviour {
public Texture[] texList;
int curTex = 0;
void Start () {
StartCoroutine(Switch());
}
IEnumerator Switch(){
yield return new WaitForSeconds(1);
renderer.material.mainTexture = texList[curTex];
curTex = (curTex+1) % texList.Length; // A convenient way to loop an index
StartCoroutine(Switch());
}
}
A few quick notes regarding your original script:
- As written, the
MyMethod()
coroutine starts, waits one second, then ends.
- Coroutines do not “block”, i.e., a function that calls one does not wait for it to finish before continuing.
- The for loop in
Update()
will run through all its iterations every time Update()
is called (i.e., once per frame) and thus cycle through all the textures every frame.