Reputation: 9065
We want the score displayed in our game to be a specifically designed number font.
We got the numbers in the format of png from 0
~9
and I think it will be neat to put those in a Texture[]
array and display it accordingly.
Following is the desplay controller script
public class StepDespController : MonoBehaviour {
public static StepDespController instance;
private int step = 0;
[SerializeField]
public Texture[] numberTextures;
private void Awake()
{
if(instance == null)
{
instance = this;
}
}
public void addStep(int step)
{
this.step += step;
}
private void OnGUI()
{
char[] array = step.ToString().ToCharArray();
Debug.Log(array);
for (int i = 0; i < array.Length; i++)
{
GUI.DrawTexture(new Rect(0 + i * 30, 0, 20, 30), numberTextures[(int)char.GetNumericValue(array[i])]);
}
}
}
And following is the binding of the textures of the digitals from 0
~9
:
But I found it will not display anything in the game scene, what was I missing?
Thanks.
Upvotes: 0
Views: 140
Reputation: 5930
Here is your problem :
char[] array = step.ToString().ToCharArray();
Debug.Log(array);
for (int i = 0; i < array.Length; i++)
{
GUI.DrawTexture(new Rect(0 + i * 30, 0, 20, 30), numberTextures[(int)char.GetNumericValue(array[i])]);
}
Instead of doing it that way I would suggest you to simply use this :
const int offset_step = 30; // declare standard step size
int offsetX = 0; // declare starting x offset
foreach(char c in step.ToString()) // iterate through all characters in your score value as string value
{
// draw texture on index `char - (char)'0'`
GUI.DrawTexture(new Rect(offsetX, 0, 20, 30), numberTextures[(int)(c - 0x30)]);
offsetX += 30; // increase offset
}
To extend this answer a bit. char
is 2 bytes wide numeric representation of character ( either printable or not ). Since you want to display only numeric values you have to remember that these values starts from 0
which is 0x30
and ends up with 9
which is 0x39
in ASCII and same within CP1251 which is used by C#. Now all you have to do, because your 0
texture is the "0th" element in your array, is to subtract beginning of the ASCII numeric characters from your character.
Simple example :
char zero = '0'; // 0x30
char one = '1'; // 0x31
// when you do `one == 1`
// it translates to `0x31 == 0x01` which is false
// now consider this `one - zero == 1`
// above will return true because
// 0x31 - 0x30 == 0x01
// 0x01 == 0x01
Upvotes: 1