Search Unity

Connecting text from one panel to another

Discussion in 'Scripting' started by kcudom, May 13, 2021.

  1. kcudom

    kcudom

    Joined:
    May 13, 2021
    Posts:
    1
    Hello! is text that will appear on a dialogue Panel that will connect to a journal Panel upon clicking a submit Button. Currently getting the following error:

    NullReferenceException: Object reference not set to an instance of an object
    FirstPersonController.OnTriggerEnter (UnityEngine.Collider other) (at Assets/_Scripts/FirstPersonController.cs:93)

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class FirstPersonController : MonoBehaviour
    {
    public GameObject dialoguePanel;
    public GameObject infoText;
    public GameObject journalPanel;​

    if (other.gameObject.name == "Pakal")
    {
    (line 93) infoText.GetComponent<UnityEngine.UI.Text>().text = "Hello!";​
    }
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,929
    No doubt Kurt-Dekker will be coming in with his usual post in a moment. But the bottom line of a null reference error is always the same: you're trying accessing something that's not there. You just need to find out why it's not there.

    Could be the object doesn't have a text component, or you haven't assigned the gameobject in your inspector for whatever has this FirstPersonController script. Seems to be the most likely here.

    Bit of advice, if you're ever using GetComponent, assign it to a variable then check for null. Like so:

    Code (CSharp):
    1. Text infoTextComponent = infoText.GetComponent<Text>();
    2. if (infoTextComponent != null)
    3. {
    4.     //do whatever thing you want to do
    5. }
    And you can put else/else if cases in case whatever you want to be there isn't there, without hitting a game stopping null reference error.
     
    Lurking-Ninja likes this.