0

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?

Eoghan Hynes
  • 41
  • 11

1 Answers1

0

Either declare CT as public (or add the [SerializeField] tag above it), and drag & drop the gameObject holding the ChangeText component in the inspector.

public class SpacePress : MonoBehaviour 
{
    [SerializeField]
    private ChangeText CT; // Drag & drop in the inspector

}

Another solution (less advised), is to keep CT private and use one of the GetComponent or Find functions to retrieve it:

public class SpacePress : MonoBehaviour
{
    private ChangeText CT;

    // Use this for initialization
    void Start ()
    {
        CT = FindObjectOfType<ChangeText>();
        // OR
        // CT = GameObject.Find("NameOfTheObjectHoldingCT").GetComponent<ChangeText>();
    }
}
Hellium
  • 7,206
  • 2
  • 19
  • 49
  • HI, I used: CT = GameObject.Find("Text").GetComponent(); in the start() method because ChangeText() is all ready added as a component for the Canvas.Text. But I still get One NullReference error before I can change text. Can I solve this one off error? – Eoghan Hynes Apr 16 '18 at 08:56
  • `GameObject.Find` will retrieve **a** GameObject named `Text`. The problem is that you may retrieve the wrong gameObject. Rename the gameObject to have a unique name. But I highly advise you to go for the 1st solution. – Hellium Apr 16 '18 at 09:27
  • I'd like to go for the first solution. but what do i drag to the inspector? the script is already there under the Text object. – Eoghan Hynes Apr 17 '18 at 13:19
  • As I said, you have to put a public / serialized reference of the `ChangeText` instance inside your `SpacePress` script. Then, drag & drop the object holding the `ChangeText` script inside the `CT` field inside the `SpacePress`'s inspector. – Hellium Apr 17 '18 at 21:20