统一使用图像取代分数

unity using image to desplace score

我们希望游戏中显示的分数是专门设计的数字字体。 我们从 0~9 中获得了 png 格式的数字,我认为将它们放在 Texture[] 数组中并相应地显示它会很整洁。

以下是显示控制器脚本

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])]);
        }
    }
}

下面是0~9的数字贴图绑定:

但是我发现它在游戏场景中不会显示任何东西,我错过了什么?

谢谢。

这是您的问题:

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])]);
}

我建议您不要那样做,而是简单地使用这个:

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
}

稍微扩展一下这个答案。 char 是字符的 2 字节宽数字表示(可打印或不可打印)。由于您只想显示数值,因此您必须记住这些值从 0 开始,即 0x30 并以 9 结束,即 ASCII 中的 0x39 和内部相同C# 使用的 CP1251。现在你所要做的就是,因为你的 0 纹理是数组中的“第 0 个”元素,所以你需要从你的字符中减去 ASCII 数字字符的开头。

简单示例:

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