- Home /
Incrementing and decrementing a text value for a trade
Im attempting to add and minus from a text value using buttons. What my script currently does is - when I +++++ it shows 5, then I use the - button 3 times and it gives me -3, I then use + and I get 6. I hope this makes it clear.
public class PlusMinusScript : MonoBehaviour {
private int textNumber;
public Text TextObject = null;
public void addOne(){
if (TextObject != null) {
textNumber++;
TextObject.text = textNumber.ToString ();
}
}
public void minusOne(){
if (TextObject != null) {
--textNumber;
TextObject.text = textNumber.ToString();
}
}
}
Are you sure you have only one script Plus$$anonymous$$inusScript
to a gameobject ? You must not attach this script to your 2 buttons. Only one GameObject must hold this script, then, select your buttons, drag & drop the object holding this script and call the appropriate functions.
Do you only use one instance of this component? If there are multiple instances (ie you have one for Plus and one for $$anonymous$$inus), then this will happen as they both have their own values for textNumber.
Well not quite, we're asking if you've maybe got two "Plus$$anonymous$$inusScript" components sitting in your scene, with your two "Plus" and "$$anonymous$$inus" buttons each looking at unique ones.
Ah, yes. Each button has a plus$$anonymous$$us script on it. This is where I am getting confused
Then that is probably the issue. :-)
Remove one and have your buttons reference the same instance of that script.
edit: alternatively, you can just make the textNumber static
if you only intend to have one number like this ever exist and be shared across other objects, but that might start you on bad habits with other situations.
I, unfortunately, have 5 values that need to be incremented and decremented.
YAYAYAYYY!!!! Thank you so much for your help and patience @TreyH
Answer by Hellium · Mar 16, 2018 at 07:09 PM
As expected, you have attached the PlusMinusScript
script to two scripts. Since the value of textNumber
is not shared between these two scripts, your problem occurs.
Attach the
PlusMinusScript
to only one gameObject (to your TextObject for example)Drag & Drop the gameObject holding the
Text
component to the public field of thePlusMinusScript
Select your first button, drag & drop the gameObject in step #1, and select the
addOne
functionSelect your second button, drag & drop the gameObject in step #1, and select the
minusOne
function
Your answer
Follow this Question
Related Questions
Need help with array script 1 Answer
Invisible Models in Unity??? 5 Answers
class array removeAt 1 Answer
.Add not a function of my array. 1 Answer
`Inventory' does not contain a definition for `Add' 2 Answers