- Home /
Subtracting random numbers instead of 1
I'm a beginner when it comes to scripting, and I've run into this weird problem.
What I'm trying to do is that when you click a button, the amount of wood goes down by 1, but instead of subtracting just 1 it subtracts (appearently) random numbers like -43 and so on. Please take a look at my code and tell me why this is?
public int wood;
public Text woodText;
public Button stokeButton;
void Start () {
wood = 10;
}
void Update () {
woodText.text = "Wood: " + wood;
stokeButton.onClick.AddListener(() => {
//handle click here
wood -= 1;
});
}
Answer by tanoshimi · Mar 15, 2015 at 07:10 PM
You're adding an additional onclick listener every time the Update() loop runs, and every single one subtracts another -1 from wood. Add the listener once, in Start():
void Start () {
wood = 10;
stokeButton.onClick.AddListener(() => {
wood -= 1;
});
}
void Update () {
woodText.text = "Wood: " + wood;
}
Your answer
Follow this Question
Related Questions
Beginners question - unity 4.6 uGui Button - Which button was clicked? 2 Answers
uGUI Button without renderer 3 Answers
instantiate a button in a panel in new uGUI 1 Answer
UGUI UI, How to increase Hitzone, Click area, Button Rect, respectivlly to the Image component? 7 Answers
IPointerClickHandler error 2 Answers