0

I'm completly new to unity, so I'm following a tutorial on youtube. I tried to make a "clear" button on unity for a Notepad App for Android. But when I clicked it, it gave me an error on the console:

NullReferenceException: Object reference not set to an instance of an object
ButtonControl.ClearText () (at Assets/Scripts/ButtonControl.cs:12)

This is the Script I used:

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

public class ButtonControl : MonoBehaviour
{
public GameObject theText;

    public void ClearText()
    {
        theText.GetComponent<InputField>().text = "";
    }
}

Note: the tutorial I'm following is this: NOTEPAD | HOW TO MAKE AN APP IN UNITY TUTORIAL #3 - C# CODING | TEXTURES https://www.youtube.com/watch?v=7LEeKMgmFsg&list=PLZ1b66Z1KFKjbczUeqC4KYpn6fzYjLKoV&index=3 by Jimmy Vegas

Albina
  • 1,901
  • 3
  • 7
  • 19
Alex
  • 1
  • 3

1 Answers1

-1

is input field null?

try:

using UnityEngine;
using UnityEngine.UI;

public class ButtonControl : MonoBehaviour
{
    public InputField inputField;

    public void ClearText()
    {
        inputField.text = "";
    }
}

In short, the null is bc the Component or Object is null. above shows how this would work if not. It is referring to an object not instantiated when this script runs.

Mason
  • 1,662
  • 1
  • 9
  • 10
  • Did you reference the InputField in the Inspector? – derHugo Feb 22 '23 at 18:57
  • GameObject named as 'theText' vs using the InputField (which is meant for text and he can do .text like he is attempting that way. it isnt my game so not sure what you are asking. I cant see his setup in his inspector and Im just reading and guessing off the api docs. I do use unity but been a while so I could be wrong. ref: https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.InputField.html see 'text' as part of input field here. – Mason Feb 22 '23 at 23:29
  • I'm not asking you .. OP had commented that this was still throwing a null ref exception so OP forgot to assign the field via the Inspector .. OP has apparently removed their comment after mine ;) – derHugo Feb 23 '23 at 09:59
  • can you delete above and ask OP not me – Mason Feb 28 '23 at 19:28