前文:https://blog.csdn.net/Jaihk662/article/details/86772256(UILabel显示字体)
一、游戏得分信息
第一步:新建UILabel,并将NGUI的摄像机的视角设定和主摄像机一致(比忘了Align……)
第二步:新建两个Label标签,设定第一个文字内容为:“你的分数”,第二个文字内容为分数值
修改分数对齐为左对齐,如下:不然当分数位数增加时,分数会和前面的文字重叠
两个文字的Overflow都设置为ResizeFreely(边框大小和字体大小自动同步)这也是最常用的
到这里基本就搞定了
二、代码控制文字
一些重要API/方法:
- private UILabel scr = GameObject.Find("Score1").GetComponent<UILabel>():获取Score1的UILabel组件
- UILabel.text:显示的文字内容(string类型)
- UILabel.col:显示的文字颜色(Color.red等)
- ……
数字与String类互相转换:
- int p = int.Parse(string):string转数字p
- scr.text = p.ToString():p转string
那么现在就可以给前面的打砖块小游戏添加一个功能:每当一个小方块被打下去,分数增加1
方块销毁脚本修改如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeDes : MonoBehaviour
{
private UILabel scr;
private Transform myTran;
void Start()
{
scr = GameObject.Find("Score1").GetComponent<UILabel>();
myTran = gameObject.GetComponent<Transform>();
}
void Update()
{
if (myTran.position.y<=-10)
{
GameObject.Destroy(gameObject);
int p = int.Parse(scr.text);
if (p >= 10)
scr.color = Color.yellow; //当分数超过10时,将分数颜色改为黄色
scr.text = (p + 1).ToString();
}
}
}
搞定!演示如下: