- Home /
DropDown menu(add item from input field): Object reference not set to instance of an object C#
My goal is: Type into the input field -> press the button "Enter" -> have that added to the drop down list.
My question is -> How do I get rid of this NullReferenceException Error?
And if at all possible, how can I make this work?
The Error I am getting is this.
NullReferenceException: Object reference not set to an instance of an object DdMenu.addItem()(at Assets/Scripts/DdMenu.cs: 20)
Here are my two scripts.
First script : This is for adding the options into the dropdown menu
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DdMenu : MonoBehaviour {
AddOption ao;
public Text selectedName;
public Dropdown drop;
public void dropIndex(int varIndex){
selectedName.text = ao.menuList[varIndex];
}
public void addItem(){
drop.AddOptions (ao.get_holder()); //Error is here
}
}
Second Script: This is for getting the text from the input field.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class AddOption : MonoBehaviour {
public List<string> menuList;
public Text test;
private string x;
public void getText(){
x = test.text;
menuList.Insert (0, x);
}
public List<string> get_holder(){
return menuList;
}
}
I figured it out actually. Ill post the answer later.
Watch my video on how to do this... https://youtu.be/wIxYihzCFs$$anonymous$$
View the Source Code Here :
https://zakalberda.com/2017/05/09/unity-dropdown-add-and-delete-with-a-button/
Answer by phxvyper · May 09, 2017 at 04:15 PM
Read the error. One of the objects you're attempting to access data from is null.
On line 20
drop.AddOptions (ao.get_holder());
you have two objects you're attempting to act upon: drop
and ao
.
You have to assign these objects either in code or in the editor before attempting to use them like this.
Your answer
![](https://koobas.hobune.stream/wayback/20220612121549im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to play scrolling sounds when scrolling through ScrollRect? 1 Answer
Help With Adding Buttons To Panel 4 Answers
List to dropdown 0 Answers
A node in a childnode? 1 Answer
dropdown menu after effects 1 Answer