- Home /
How to generate a string of zeroes based on a pre-determined algorithm?
I have the following code in place, and would like to condense the content of 'Update' down to a few lines at maximum. The code determines what an on-screen score counter displays, depending on the string length of the score.
using UnityEngine;
public class ScoreCounter : MonoBehaviour
{
public int score;
public GameObject GameManager;
void Update ()
{
score = GameManager.GetComponent<GameLoop>().stats.score;
if(score.ToString().Length == 1)
{
this.GetComponent<TextMesh>().text = "Score: 0000" + score + "000";
}
else if(score.ToString().Length == 2)
{
this.GetComponent<TextMesh>().text = "Score: 000" + score + "000";
}
else if (score.ToString().Length == 3)
{
this.GetComponent<TextMesh>().text = "Score: 00" + score + "000";
}
else if (score.ToString().Length == 4)
{
this.GetComponent<TextMesh>().text = "Score: 0" + score + "000";
}
else if (score.ToString().Length == 5)
{
this.GetComponent<TextMesh>().text = "Score: " + score + "000";
}
}
}
I've calculated the number of zeroes needed in the first 'Score' string, which is:
5 - score.ToString().Length
I'm fairly sure that the next step here is to implement it as follows:
this.GetComponent<TextMesh>().text = "Score: " + 'insert code here with algorithm calculating zero count' + score + "000";
So the question is, what goes in that space, and if I'm completely wrong, what's the solution?
Thanks in advance for any help.
Answer by JedBeryll · Aug 26, 2016 at 05:14 AM
this.GetComponent().text = score.ToString("D5");
will always make it look like 5 digits.
And to get the desired output you would add the 3 zeros at the end:
score.ToString("D5") + "000";
Or what would also work (but is less efficient) is to multiply the number by 1000 before you turn it into a number with 8 digits:
(score*1000).ToString("D8");
The first one is better since it keeps the full range of the integer value. However since you only show 8 digits it would be still enough since an integer can go up to 2147483647.
Your answer

Follow this Question
Related Questions
C# cannot convert 'char' expression to type 'UnityEngine.Texture' 1 Answer
Cannot convert 'String' to 'float (but im actualy converting a float to a string) 2 Answers
Having problems with Thread and ToString 0 Answers
Converting fastParseInt to JS from C 1 Answer
Change a variable with ToString() 2 Answers