Add "1" to score text? Not "11111"?
Hello,
I would like to make a script that adds "1" to a text object every time a sprite is clicked.
When the sprite is clicked, however, it disappears, spawning a new sprite. My problem is that the game thinks that I literally want to add "1" to the text, resulting in "11111" instead of "5".
Main Script Code:
public class ScoreHandler : MonoBehaviour {
public static ScoreHandler instance;
// Use this for initialization
void Awake () {
instance = this;
}
public Text powerUpMessageCanvas;
// Update is called once per frame
void Update () {
}
}
Called from the script on the sprite(s):
public class DestroyScript : MonoBehaviour {
private void OnMouseDown()
{
Destroy(gameObject);
ScoreHandler.instance.powerUpMessageCanvas.text += 1;
}
}
Thanks in advance, Aiden
Answer by TimBur · Aug 31, 2018 at 04:59 PM
This is an issue of operators and data types. The same operator can do different things to different data types. Context matters. Specifically, the "+" operator does addition with int and float and double type variables, but it concatinates (glues together) string type variables. And the variable ScoreHandler.instance.powerUpMessageCanvas.text is a string.
What you need is a new variable of type int. You use the int to keep score, and when it changes, you convert the int to a string and copy that string into ScoreHandler.instance.powerUpMessageCanvas.text
//In ScoreHandler, you create a new variable
int score = 0;
//When things are destroyed, you change the int in ScoreHandler
score +=1;
//AND you convert the int to a string, and put the string in the display text
{stuff}.text = score.ToString();
Your answer
Follow this Question
Related Questions
Countdown Timer 2 Answers
How do I keep two UI text unity3d on the scene 2 Answers
arrow from text to object - complete beginner 0 Answers
UI Text created from C# Script 0 Answers
I have no Idea why my highscore Script isn't working ... 0 Answers