- Home /
Creating a UI list at runtime programmatically
I have a scene where I should be able to select a 3D model from a list of items, which will then be loaded into the next scene. I want to generate the list of items programmatically, based on what is already stored in the local database. But I have problems getting the list of items to be displayed in the scene ...
So I have a class for the items:
[System.Serializable] public class Item {
public string ObjectGuid;
public string Name;
public string Description;
public Sprite Icon;
public Button.ButtonClickedEvent SelectObject; }
A script for my scene, that contains a list of items and a method that I call to load the objects from the database:
public class ObjectSelectionScript : MonoBehaviour {
public List<Item> itemList;
public Transform contentPanel;
void LoadObjects() {
StreamReader str = new StreamReader (Application.persistentDataPath + "/" + DataManager.LOCATION_XML_PATH);
string result = str.ReadToEnd ();
str.Close();
var jo = SimpleJSON.JSON.Parse (result);
if (jo ["Objects"] != null) {
for (int i = 0; i < jo["Objects"].Count; i++) {
if (!string.IsNullOrEmpty(jo["Objects"][i]["FileGuid"])) {
Item newObject = new Item();
newObject.ObjectGuid = jo["Objects"][i]["ObjectGuid"];
newObject.Name = jo["Objects"][i]["Name"];
newObject.Description = jo["Objects"][i]["Description"];
//newObject.SelectObject = new Button.ButtonClickedEvent();
itemList.Add(newObject);
}
}
}
}
A ModelObject class:
public class ModelObject : MonoBehaviour {
public Button button;
public Text Name;
public Text Description;
public Image Icon;
}
And a prefab ModelObjectPrefab that contains Name, Description, a Thumbnail, added to my assests folder.
The PopulateList() method is my problem. I can't get to instatiate the prefab and then create ModelObjects that I can throw in the contentPanel in the interface. This is my code:
void PopulateList()
{
try {
foreach (var item in itemList)
{
GameObject newModel = Instantiate(ModelObject) as GameObject;
ModelObject myModelObject = newModel.GetComponent<ModelObject>();
myModelObject.Name.text = item.Name;
myModelObject.Description.text = item.IDescription;
myModelObject.icon.sprite = item.Icon;
myModelObject.button.onClick = item.selectObject;
newModel.transform.SetParent(contentPanel);
}
} catch (System.Exception ex) {
}
}
I currently get null pointer on instantiate. I have tried Resources.Load, and variations of the Instatiate method, but I did not find a solution.
Can anyone give me a hint what is the problem? How should PopulateList() look like to get the items to the interface?
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Add all objects of a type to a list before runtime 1 Answer
Array of vectors lost in runtime, but not null 0 Answers