- Home /
Changing text color at runtime always white...
I'm trying to change text to a specific shade by using this code:
timeColor = new Color (68f, 144f, 233f, 1f);
timerDisplay.gameObject.GetComponent<Text> ().color = timeColor;
And have also tried this:
timeColor = new Color (68f, 144f, 233f, 1f);
timerDisplay.color = timeColor
They both turn my text to white for some reason. Any ideas why?
Answer by flashframe · Sep 18, 2016 at 02:13 PM
The RGB values of a Color need to be float values between 0-1. (You can calculate these values by dividing by 255.)
If you want to use byte values, you need to use Color32 https://docs.unity3d.com/ScriptReference/Color32.html
timeColor = new Color32(68, 144, 233, 255);
Answer by Sinnii · Sep 18, 2016 at 02:15 PM
color is not a property of the text itself, but of the UI element that contains it. What you want is timerDisplay.font.material.color
And yeah, as the above answer says you need 0-1 values.
Thanks guys, that makes sense. So do I need to add a material to the font? Because even with these changes, my font is not changing (in this case to red).
if (secs >= 0) {
if (secs <= 10) {
timeColor = new Color32 (255, 70, 57, 255);
Debug.Log ("red");
if (interval > tics && tics > 0) {
source.PlayOneShot (alarm);
interval--;
}
} else {
timeColor = new Color32 (66, 154, 255, 255);
Debug.Log ("blue");
}
//timerDisplay.color = new Color(68f, 144f, 233f, 1f);
timerDisplay.font.material.color = timeColor;
timerDisplay.text = "Time: " + secs;
}
Answer by codemaker2015 · Sep 23, 2021 at 01:05 PM
You can use color attribute to provide color for the text.
It can be done by two ways -> using the color static attributes and color class constructor.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ColorDemo : MonoBehaviour {
[SerializeField]
Text infoText;
void Start () {
infoText.text = "Hello World";
infoText.color = Color.red; //Red color using Color class
//Red color using hex value. (255,0,0) => 255/255, 0/255, 0/255) => (1,0,0)
infoText.color = new Color(1f, 0f, 0f);
// Color with opacity value. 1 means opaque and 0 means transparent.
infoText.color = new Color(1f, 0f, 0f, 0.5f);
}
}