I’m trying to have randomly set float values change the colour of my text, but I can’t seem to make it work, as far as I can tell this chunk of code should work just fine.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TextColorChanger : MonoBehaviour {
public Text[] Change;
void Start() {
RainbowColour();
}
void RainbowColour() {
float rCol, gCol, bCol;
rCol = Random.Range(0, 255);
gCol = Random.Range(0, 255);
bCol = Random.Range(0, 255);
Change[0].color = new Color(rCol, gCol, bCol);
Change[1].color = new Color(rCol, gCol, bCol);
Debug.Log("rCol: " + rCol + " gCol: " + gCol + " bCol: " + bCol);
}
}
Your problem is with “while (true)”! If you want it to be updated, then use the Update method, the ONLY way to use “while (true)” in Unity is in a Coroutine.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class TextColorChanger : MonoBehaviour {
public Text[] Change;
void Start() {
StartCoroutine(RainbowColour());
}
IEnumerator RainbowColour() {
while (true) {
float rCol, gCol, bCol;
rCol = Random.Range(0, 255);
gCol = Random.Range(0, 255);
bCol = Random.Range(0, 255);
Change[0].color = new Color(rCol, gCol, bCol);
Change[1].color = new Color(rCol, gCol, bCol);
Debug.Log("rCol: " + rCol + " gCol: " + gCol + " bCol: " + bCol);
yield return new WaitForSeconds(0.5f);
}
}
}
Here is a little explanation about how to use Coroutines:
Coroutines are like a method, but that follows a routine (!), executing piece by piece after meeting the desired condition;
It should be started with “StartCoroutine(MyCoroutine());”;
The coroutine should be a Method with IEnumerator as it’s return (not “void”);
Inside it, you should use “yield return” followed by the condition that it should wait to continue it’s execution (in this case, we say that we want to wait half a second). If you use “yield return null;” if will just wait pass 1 frame. To stop the Coroutine execution you could use “yield break;”
If you would like to undestand more about how to use coroutines, take a look around, there is a plenty of answer already about it.