0

I am new to unity and am using unity 2020.3.26f1 . I am receiving an array of names from server. I want to make buttons dynamically using those names inside scroll view using c# script and assign on Click() that simply prints the name of button when its clicked. I just don't know how to create button dynamically. Following is the script I have attached to scroll View;

public string allNames; 

void Start()
{
    StartCoroutine(getNames());
}

IEnumerator getNames()
{
    UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/names");
    yield return www.SendWebRequest();

    if (www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(www.error);
    }
    else
    {
        allNames = www.downloadHandler.text;
        allNames = allNames.Replace("[", "");
        allNames = allNames.Replace("]", "");
        allNames = allNames.Replace("\"","");

        string[] separatedNames = allNames.Split(',');
        for (int i = 0; i < separatedNames.Length; i++)
        {
            Debug.Log(separatedNames[i]);
            //make buttons here and attach them to scroll View
        }
    }
}

2 Answers 2

2

I found a video that applied @ShafqatJamilKhan suggestion. Posting my code here for reference.

//content reference of scroll view
[SerializeField] Transform contentPanel;

[SerializeField] GameObject buttonPrefab;

void Start()
{
    StartCoroutine(getNames());
}

IEnumerator getNames()
{
    UnityWebRequest www = UnityWebRequest.Get("http://localhost:8080/names");
    yield return www.SendWebRequest();

    if (www.result != UnityWebRequest.Result.Success)
    {
        Debug.Log(www.error);
    }
    else
    {
        string allNames = www.downloadHandler.text;
        allNames = allNames.Replace("[", "");
        allNames = allNames.Replace("]", "");
        allNames = allNames.Replace("\"","");

       // prefab button y position and yPosition should be the same.
        float yPosition = 115;

        string[] separatedNames = allNames.Split(',');
        for (int i = 0; i < separatedNames.Length; i++)
        {
            GameObject button = (GameObject)Instantiate(buttonPrefab);               
            string name = separatedNames[i];
            button.GetComponentInChildren<Text>().text = name;

            button.GetComponent<Button>().onClick.AddListener(
                // your function whatever you want to do
                () => { customFunction(name); });

            // applying y positions so the buttons dont overlap

            button.transform.SetPositionAndRotation(new Vector3(0.0f, yPosition, 0.0f), new Quaternion(0.0f, 0.0f, 0.0f,0.0f));
            button.transform.SetParent(contentPanel,false);
            yPosition -= 35;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1
  1. Make a nice button and save it as prefab.

  2. Instantiate it or Pool it.

  3. Add onClick events.

    GameObject buttonPrefab;

     void MyAwesomeCreator()
     {
         GameObject go = Instantiate(buttonPrefab);
         var button = GetComponent<UnityEngine.UI.Button>();
         button.onClick.AddListener(() => FooOnClick());
     }
     void FooOnClick()
     {
         Debug.Log("Ta-Da!");
     }
    

Copied from Unity Forum

2 Comments

how will this button be attached to the content area of scroll View?
You also need to get reference of content area in script and make new button child of that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.