- Home /
How to change color of certain text on a canvas on click
Hi,
Unity noob here. I am working on a VR project to teach poetry in an immersive way for school and trying to accomplish the following:
The user will see a block of text of a poem on a canvas. When they use gaze to click a button, all the vowels in the poem will change color and be highlighted, or all the rhyming words in the poem will change color and be highlighte on the button click, etc.
Can anyone give me any tips (is text mesh pro the best choice?) or the code for the best way to accomplish this?
Thanks!
Answer by Somebody0 · Nov 17, 2018 at 11:15 PM
On your place i try something like that:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
public string s_Text; //Type here your text, OPTIONAL
public Text o_text; //Object with text component
public void ColorRed()
{ //Red Text
o_text.text = "<color=red>" + o_text.text + "</color>"; //WORKS ONLY WHEN YOU GET RICH TEXT + non_optiona lversion
}
public void ColorRedOptional()
{ //Red Text
o_text.text = "<color=red>" + s_Text + "</color>"; //WORKS ONLY WHEN YOU GET RICH TEXT + optional version
}
public void NormalText() //Optional
{ //Normal Text
o_text.text = s_Text;
}
}
Just apply ColorRed() to button; You can try something with RandomRange to "more randomness" or Text.color;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
public string text; //Optional
public Text o_Text;
public Color o_Color; //Change in inspector
public void ChangeColor()
{
o_Text.text = text; //Optional
o_Text.color = o_Color;
}
}
More about that: Rich text: https://docs.unity3d.com/Manual/StyledText.html Color: https://docs.unity3d.com/ScriptReference/UI.Graphic-color.html
Non-optional version: You must edit text in text prefab in inspector.
Your answer
Follow this Question
Related Questions
Change Textmesh.text from script 2 Answers
Unity crashes at writing TextMesh? 0 Answers
Adjust text file reading/detection 0 Answers