Text 2D字体的操作
1、在Hierarchy层级面板中点击鼠标右键,选择UI中的text
2、在写2D的ui的时候,在Scene视图中选择2D模式比较容易操作。
3、在C#中引入using UnityEngine.UI;
,并声明变量
4、在unity面板中进行赋值
5、物体不显示,可以在unity面板中直接进行设置:
- 如果要控制显示与隐藏,那么只需要声明Text变量,并在untiy中进行赋值即可。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Text需要声明此命名空间
using UnityEngine.UI;
public class Player : MonoBehaviour
{
private Rigidbody playerRD;
//声明Text
public Text textScore;
private int score = 0;
void Start()
{
playerRD = GetComponent<Rigidbody>();
//初始化文字
textScore.text = score.ToString();
}
// Update is called once per frame
void Update()
{
}
//当然了,写在这个方法里面是因为有其他的逻辑,也可以卸载Update方法里面
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Food")
{
score++;
//更新文字
textScore.text = score.ToString();
}
}
}
- 如果要进行ui的显示或者消失的画,声明的就不是Text变量了,而是GameObject变量
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Text需要声明此命名空间
using UnityEngine.UI;
public class Player : MonoBehaviour
{
private Rigidbody playerRD;
public Text textScore;
//声明GameObject变量才能控制这个游戏物体本身的一些属性
public GameObject winText;
private int score = 0;
// Start is called before the first frame update
void Start()
{
playerRD = GetComponent<Rigidbody>();
textScore.text = score.ToString();
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Food")
{
score++;
textScore.text = score.ToString();
Destroy(other.gameObject);
if(score == 9)
{
//该游戏物体(Text)进行显示
winText.SetActive(true);
}
}
}
}