I cant find anywhere on the net how to increase or decrease a text.
so I have a textbox on the canvas that says “0” there is a button with a + and one with - How do I go about making the buttons increment/decrement the text by 1? I’ve tried at this for hours. I am still new to unity mind you.
I have managed to get an output through the console for “you have clicked a button” but I cant figure out how to make the button change the text.
seems any video I find just shows how to change a property associated with THAT button or to change a scene, not update a text. Ill check those out and see if anything translates.
You should write a script and add a reference to your Text component. Then with your buttons OnClick event add the reference to the script and select the corresponding method to increment/decrement an internal value in the script. Finally, set the text of TextObject to your value as a string.
Example:
public class IncrementText : MonoBehaviour
{
public int Value = 0;
public Text TextObject = null;
public void Increment()
{
if (TextObject != null)
{
++Value;
TextObject.text = Value.ToString();
}
}
public void Decrement()
{
if (TextObject != null)
{
--Value;
TextObject.text = Value.ToString();
}
}
}
^ with that, do I need to rename my text component back to text? Right now its rtPlrLife (as there will be a 2nd one Im doing this too as well)
update I changed my text component’s name to Text and added the using UnityEngine.UI.Text and it at least got rid of any errors. though I don’t know how to tie in the rest to make it work.
using UnityEngine;
using System.Collections;
public class IncrementText : MonoBehaviour
{
public int Value = 0;
public UnityEngine.UI.Text TextObject = null;
public void Increment()
{
if (TextObject != null)
{
++Value;
TextObject.text = Value.ToString();
}
}
public void Decrement()
{
if (TextObject != null)
{
--Value;
TextObject.text = Value.ToString();
}
}
}
As suggested, you really should look at some beginner tutorials if you’re struggling with this part. Setting up buttons in the inspector and dragging stuff into slots to fill public variables should be part of your basics. You’re only going to struggle with the entire project you are trying to do.
You should be able to tie the two methods to your buttons and tie your text box to the text variable, which you could name whatever you want, especially since you plan to have two and they can’t be named the same. Also, it’s probably better just to add the UnityEngine.UI as a using instead of having to place it in front of all the variables that are UI variables.