- Home /
Beginners question - unity 4.6 uGui Button - Which button was clicked?
I have 4 buttons, 3 with a random value and one with the the correct answer. I am trying to write a single method to attach to the button which will check to see if the value in the buttons text box is the same as the correct answer.
Currently I have four different methods - one for each button
public void CheckAnswer () {
if (button1.GetComponentInChildren<Text>().text == value3.ToString())
{
question.text = "yay";
}
else
{
question.text = "boo";
}
}
However, I am trying to get something more like
if ("Button clicked".GetComponentInChildren<Text>().text == value3.ToString())
Answer by Zodiarc · Sep 30, 2014 at 07:21 AM
Well I would do something like a state-machine.
You will need a game object with a script attached. The script could look like this:
class AnswerChecker extends MonoBehaviour{
private var isCorrect:boolean;
public function correct():void{
this.isCorrect = true;
}
public function wrong():void{
this.isCorrect = false;
}
public function isCorrect():boolean{
return this.isCorrect;
}
}
Then you assign the "correct" function to the button with the correct answer and the "wrong" function to the buttons with the wrong answers.
This way you will be able to acess the answer from other scripts by using GameObject.Find("your object name here").GetComponent(AnswerChecker).isCorrect()
Answer by Kiwasi · Sep 30, 2014 at 08:39 AM
An alternative structure would be to have one button for the right answer and three for the wrong answer. Then scramble their positions on screen.
To answer your question you can pass in a Untiy Object as a parameter in your OnClick event. Simply pass in the GameObject of the button. Or an int that represents the button ID.
Your answer
![](https://koobas.hobune.stream/wayback/20220613164057im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Simulate Button presses through code unity 4.6 GUI 4 Answers
[Solved] why dosen't Unity 4.6 New UI button work when you instantiate it on playmode? 2 Answers
How to make a power bar with button for mobile games in unity 2d 0 Answers
Unity 4.6 Buttons not responding in second canvas? 7 Answers
Get/Set Button Text with uGUI 4.6 1 Answer