- Home /
How can I use sprites as numbers?
I have 0-9 numbers as sprites. I dont want to show score with text. I want to show the score with those sprite numbers 0-9? and it should be for example 17 like 1-7. is it possible to do it? or i can do it by using only fonts?
Answer by Dave-Carlile · Aug 03, 2015 at 07:27 PM
Yep, you can do this. It's a little work though. The basic idea is that you get each digit of the number which will be from 0 through 9, and use that as an index into an array of prefabs for the equivalent digit image...
// initialize a sprites array with the a prefab for for each digit,
// making sure the 0 index points to the 0 sprite image, and the 9 index
// points to the 9 sprite image - left as an exercise for the reader -
// should be able to do this in the editor if you make it a public property
GameObject[] sprites = new GameObject[10]
int value = 4143; // make sure the data type is an integer
// this is the key part, converting an integer score into your sprites
while (value > 0)
{
// get the 1's place value - % is the modulo operator which
// divides by the the specified value and returns the remainder,
// e.g. 4143 % 10 = 414 with a remainder of 3, so it returns the value 3
// which is the digit in the 1's place
int digit = value % 10;
// TODO : create and position sprite instance from sprites[digit]
// remember that we're going from the right to left
// move the 10's place to the 1's place
// the first time through value is 4143, so dividing by 10 gives us 414
value /= 10;
}
Note that you're building things from right to left - i.e. each time through the loop you're getting the value in the ones place. You'll have to have a special case where value starts out at 0. And maybe some other edge cases I didn't think of. But this should give you the basic idea.