André Foote
André Foote

Reputation: 368

How to display list in gui in runtime

I'm trying to create a search interface similar to Facebook's. That is, you type in all or part of a name, and the matches are displayed in a list below.

I know how to extract the input from the InputField (SearchBar) but I don't know how to display the matching results in the panel below during runtime.

Create a new label/button for each match and append to... the panel? What container should I use? How do I actually "add/append"?

Any help would be much appreciated.

Here is my scene:

enter image description here

And here is my code:

using UnityEngine;
using UnityEngine.UI;
using System;

public class SearchScript : MonoBehaviour {

    public InputField SearchBar;
    public GameObject Panel;
    public List<String> myList;

    public void Start() {

        myList = new List <String>();
        myList.Add("Andre");
        myList.Add("Angela");
        myList.Add("Temi");
        myList.Add("Tupac");
        myList.Add("Graham");
        myList.Add("Grandpa");
        myList.Add("Michael");
        myList.Add("Miguel");

        SearchBar.onValueChanged.AddListener(delegate {ValueChangeCheck(myList); });
    }

    public void ValueChangeCheck(List<string> myList) {

        string contents = SearchBar.text;

        List<String> outList = new List <String> ();

        for (int i = 0; i < myList.Count; i++) {
            if (myList [i].Contains (contents)) {
                outList.Add (myList [i]);
            }
        }

        for (int i = 0; i < outList.Count; i++) {
            >>HELP<<
        }
    }
}

Upvotes: 0

Views: 432

Answers (1)

Blair
Blair

Reputation: 6693

This page in the Unity manual describes what you'll need to do in general terms. The first thing you'll want to do is (in the editor) make a blank button/label or whatever it is you want your final product to look like. For this example, I'm going to act like it's going to be a button. Once you've got the button looking the way you want, set the position to (0,0) and make it a prefab. Make a public field in your MonoBehaviour and drag the prefab into it in the editor. That will look like this:

public GameObject ButtonPrefab;

Next, in your loop, you'll need to instantiate each button, making sure that you parent the new object to your canvas (which is your SearchBar's parent, so we have an easy way to get at it). Then assign your text and shift it down and you'll be golden!

for (int i = 0; i < outList.Count; i++) {
    var newButton = Instantiate(ButtonPrefab,SearchBar.transform.parent,false) as GameObject;

    // This assumes you have a Text component  in your prefab
    newButton.GetComponent<Text>().text = outList[i];  

    // You'll just have to experiment to find the value that works for you here
    newButton.transform.position += Vector2.down * 20 * (i + 1); 
}

Upvotes: 3

Related Questions