Unity 3D:实时更新画布上的UI元素

本文介绍了如何在Unity 3D中通过脚本实时更新游戏画布上的UI元素,特别是文本。通过使用静态关键字,可以在不同脚本间共享状态,实现在子弹击中目标时动态更新分数的功能。此外,还鼓励读者探索更多UI元素如图像、滑块和按钮的使用。
摘要由CSDN通过智能技术生成

In the last tutorial we learned how we can add a Text label UI Element to our Game canvas.

在上一教程中,我们学习了如何将文本标签UI元素添加到我们的游戏画布。

We could have easily done that by just importing a sprite, right? Why did we bother making a Canvas? One of the major reasons is because we want to have the option of being able to modify the text, counters and images using a script. In fact, let's try that out!

我们只要导入一个精灵就可以轻松做到这一点,对吗? 我们为什么要麻烦制作画布? 主要原因之一是因为我们希望能够使用脚本来修改文本,计数器和图像。 实际上,让我们尝试一下!

Clear the Text Field from the Text gameObject, so that it doesn't say anything.

从“ 文本”游戏对象中清除“文本字段”,使其不发任何声音。

Text UI element with empty text field

Create a new script called ScoreBehavior and open it up.

创建一个名为ScoreBehavior的新脚本并将其打开。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ScoreBehaviour : MonoBehaviour
{
    private Text thisText;
    private int score;
    
    void Start()
    {
        thisText = GetComponent<Text>();
        
        // set score value to be zero
        score = 0;
    }
    
    void Update() 
    {
        // When P is hit
        if(Input.GetKeyDown(KeyCode.P))
        {
            // add 500 points to score
            score += 500;
        }
        // update text of Text element
        thisText.text = "Score is " + score;
    }

}

NOTE: Line number 4 is quite an important code line here. Your IDE will give you a Missing

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值