Unity3D之NGUI基础3.1:代码控制UILabel

 

前文: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类互相转换:

  1. int p = int.Parse(string):string转数字p
  2. 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();
        }
    }
}

搞定!演示如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值