Class ChangeText is a child of a UI.Canvas.Text:
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);
}
}
The calling class SpacePress() calls ChangeText.ChangeTheInstruction() to change the Ui.Canvas.Text.text when the user presses the space bar. This class is a child of the main camera.
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");
}
}
}
I get a NullReferenceException from the CT object, because CT is not instantiated, but I cant use 'new' on a Monobehaviour. How do I do this properly?