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.
从“ 文本”游戏对象中清除“文本字段”,使其不发任何声音。
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