- Home /
Question by
broswhocode8 · Feb 14, 2020 at 09:27 PM ·
colors
Can you change colors every secend for text?
I wanted to know if it's a way for me to change the color of my main menu text every sec
Comment
Best Answer
Answer by phosphoer · Feb 14, 2020 at 09:38 PM
Sure, one way of doing this would be by running a coroutine which updates the color every second. I wrote an example class which does this and sets the color of a UnityUI Text object to a random color. I wrote this outside of Unity so its possible it has some small errors, but it should give you the general idea of how to accomplish this. You could make the _targetText an array so it affects multiple text objects, or add this script to each text object you have.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ColorChanger : MonoBehaviour
{
[SerializeField]
private Text _targetText = null;
[SerializeField]
private float _changeInterval = 1;
[SerializeField]
private Color[] _possibleColors = null;
private void OnEnable()
{
// Kick off the change color routine, which is automatically stopped by OnDisable
StartCoroutine(ChangeColorAsync());
}
private IEnumerator ChangeColorAsync()
{
// Create a wait object based on our interval, outside of loop to avoid extra allocations
var wait = new WaitForSecondsRealtime(_changeInterval);
while (enabled)
{
// Change text color to one of our possible colors
_targetText.color = _possibleColors[Random.Range(0, _possibleColors.Length)];
// Wait
yield return wait;
}
}
}
Your answer