Class ChangeText 是 UI 的子级。画布文本:
using UnityEngine;
using UnityEngine.UI;
public class ChangeText : MonoBehaviour {
Text Instruction;
// Use this for initialization
void Start () {
Instruction = GetComponent<Text>();
Debug.Log("Instruction: " + Instruction.text);
}
// Update is called once per frame
void Update () {
}
public void ChangeTheInstruction(string inst)
{
Instruction.text = inst;
Debug.Log("Instruction is now: " + Instruction.text);
}
}
调用类 SpacePress(( 调用 ChangeText.ChangeTheInstruction (( 以在用户按空格键时更改 Ui.Canvas.Text.text。此类是主相机的子级。
using UnityEngine;
public class SpacePress : MonoBehaviour {
ChangeText CT;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("space"))
{
Debug.Log("Space pressed");
CT.ChangeTheInstruction("NewInstruction");
}
}
}
我从 CT 对象中获得了 NullReferenceException,因为 CT 没有实例化,但我不能在 Monobehavior 上使用"new"。如何正确执行此操作?
要么将CT
声明为公共(或在其上方添加[SerializeField]
标签(,然后在检查器中拖放包含ChangeText
组件的游戏对象。
public class SpacePress : MonoBehaviour
{
[SerializeField]
private ChangeText CT; // Drag & drop in the inspector
}
另一种解决方案(不太建议(是将CT
保密并使用GetComponent
或Find
函数之一来检索它:
public class SpacePress : MonoBehaviour
{
private ChangeText CT;
// Use this for initialization
void Start ()
{
CT = FindObjectOfType<ChangeText>();
// OR
// CT = GameObject.Find("NameOfTheObjectHoldingCT").GetComponent<ChangeText>();
}
}