- Home /
Change Colour from String
using UnityEngine;
using System.Collections;
public class texttest1 : MonoBehaviour {
/*
All variables are made public in order to be viewed easily in The Inspector…
*/
public string Text = “Enter Text here”;
public bool Toggle = false;
public Color change= Color.blue;
void Start(){
}
void Update(){
if(Text == null)
Debug.LogError(“Input Text is currently not there. Please enter something.”);
elseif(Text == “clear”){Text = null;}
elseif(Text == “Color.blue”){camera.backgroundColor = change}
else{Debug.Log(Text);}
if(Toggle == True) {Text = null;}
}
void OnGui(){
Text = GUI.TextField(new Rect (25, 25, 100, 30), Text );
Toggle = GUI.Toggle (new Rect(25, 125, 100, 30), “Toggle”);
}
}
I want to change this code so that, when one enters a colour, the camera.backgroundColor changes to what was entered. Is there any way I can take the string input and assign it as a colour? I already placed a short line for the input being blue.
Answer by Eric5h5 · Jun 05, 2014 at 03:28 PM
Create a Dictionary, specifically Dictionary< string, Color >
, and assign a bunch of strings with the appropriate Colors. Naturally you'd want to check if the string exists in the dictionary when the user enters a string.
Answer by Jeff-Kesselman · Jun 05, 2014 at 03:28 PM
Yes.
Use a switch statement.
eg
switch(myString){
case "red":
camera.bachgroundColor=Color.red;
break;
case "blue":
camera.bachgroundColor=Color.blue;
break;
}
Alternately you could put the colors in a Dictionary with the string as the key and the color as the value.
Finally, you could specify the color in numbers in a string (e.g. "255,128,7"), parse them out, and use the Color constructor that takes RGB values.
You can also use the dic.TryGetValue to instantly get the color value to assign , rather than using a switch statement
Your answer
Follow this Question
Related Questions
Changing a material colour of an object c# 1 Answer
Texts Highlighted at certain time (Karaoke like for spelling storytelling) 0 Answers
making bold word or coloured letter in a string, 2 Answers
Help! Iphonekeyboard has only number appear in textfield 0 Answers
Using GUI.FocusControl on TextField selects all text 4 Answers