Other
Change color from script
I'm making an app for school with a question and 3 answers. 1 answer is good and the other 2 are false. Now i want to change the color of the button to green if it's good and to red if it's false. I want to do this from the inspector, but i don't know how to apply this to the button.
This is my script.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class LevelManager : MonoBehaviour {
// answers
public string Question;
public string answer1;
public string answer2;
public string answer3;
// colors
public Color FalseAnswerColor;
public Color GoodAnswerColor;
// get the text elements
public UnityEngine.UI.Text Questiontext;
public UnityEngine.UI.Text Answertext1;
public UnityEngine.UI.Text Answertext2;
public UnityEngine.UI.Text Answertext3;
// get the button elements
public UnityEngine.UI.Button AnswerButton1;
public UnityEngine.UI.Button AnswerButton2;
public UnityEngine.UI.Button AnswerButton3;
void Start ()
{
Questiontext.text = Question;
Answertext1.text = answer1;
Answertext2.text = answer2;
Answertext3.text = answer3;
}
/*
// The answer is true
public void RightAnswer ()
{
// reward animation
// Create the reward animation and implement it
// change the color to green
}
*/
// The Answer is false
public void FalseAnswer ()
{
// change the color the red
}
}
Answer by SniperEvan · Oct 24, 2015 at 06:31 AM
Get a reference to the button you are changing. (Either thru the click event or by passing it to the method as a parameter somehow)
Set the color of the button. Unity uses color blocks for buttons so that we can have pressed color, disabled color, etc.
Psuedocode:
ColorBlock cb = button.colors;
If (answer == wrong)
cb.normalColor = FalseAnswercolor
else
cb.normalcolor = goodanswercolor
b.colors = cb; (assign the color block to the button)
Follow this Question
Related Questions
SpriteRenderer.Color not adjustable with both mecanim + script 1 Answer
Texture color completely off 0 Answers
change color 2 Answers
How to Change the Color of Text without using Markup Text? 0 Answers
Need help to make a color replace shader 0 Answers