- Home /
Creating Buttons that change an int Value
I'm creating a game where a set of questions pop up on screen with code. All the text is created with code and their placement is created with code, as well as the buttons themselves. When the player clicks on one of the buttons, depending on the button, I need to change an int value and delete that button. How can I do that?
for (int i = 3; i < readline.Length; i++)
{
askedQuestion.text = readLine[i];
RectTransform questionTransform = ((GameObject)Instantiate(question)).GetComponent<RectTransform>();
questionTransform.SetParent(questionPanel);
}
Answer by Hellium · Jun 04, 2017 at 05:41 PM
@Kishotta 's answer is correct, but incomplete, and can lead you to some problems if you are not aware. You may face the problem of closures. Take a look at the code below to prevent this problem :
private int myInt ;
// ....
for (int i = 3; i < readline.Length; i++)
{
int closureIndex = i ;
askedQuestion.text = readLine[i];
RectTransform questionTransform = ((GameObject)Instantiate(question)).GetComponent<RectTransform>();
questionTransform.GetComponent<Button>().onClick.AddListener( () =>
{
myInt = closureIndex ;
Destroy( questionTransform.gameObject ) ;
} ) ;
questionTransform.SetParent(questionPanel);
}
Thank you, that made things easier for me. There are still some problems, but I think I can take it from here.
Your answer
Follow this Question
Related Questions
buttons don't work if I use int 1 Answer
Change button icon for each without multiple GUISkins 1 Answer
How can i remove Texture on the screen 1 Answer
Changing texture of pressed button in array 1 Answer
Distribute terrain in zones 3 Answers