I am really new to coding and game development. I am creating a scene containing 10 buttons representing numbers 0 through 9 and 1 input field. I have created the attached scripts for the buttons representing numbers to allow users to enter a string of numbers into the input field using those buttons. I have used both of the following scripts by placing them in a Manager object within the scene and then attaching the script to each button as a component. I then drag the input field into the inspector. When I run the scene each button click results in the number being placed in the input field as desired. However, I continually get an error on the line including the AddListener. The error states “NullReferenceException: Object reference not set to an instance of an object”. Then is goes on to identify that specific line. Can anyone offer insight into why I am getting this error?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NumberClick : MonoBehaviour {
Button button;
public string number;
public InputField numInput;
void Start() {
button = this.GetComponent<Button>();
button.onClick.AddListener(delegate { TaskOnClick(); });
}
public void TaskOnClick()
{
numInput.text += number;
}
void Destroy()
{
button.onClick.RemoveListener(TaskOnClick);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NumberClick : MonoBehaviour {
Button button;
public string number;
public InputField numInput;
void Start() {
button = this.GetComponent<Button>();
button.onClick.AddListener(TaskOnClick);
}
public void TaskOnClick()
{
numInput.text += number;
}
void Destroy()
{
button.onClick.RemoveListener(TaskOnClick);
}
}
I have watched multiple videos and read other forums on similar problems. I have made many changes to see if the issue will be corrected, but cannot find one that fixes the problem. Several of the changes moved the reference to AddListener to a different line and the error still showed on the original line. I’m confused.