Home > Back-end >  How to add button in scroll View using script in unity
How to add button in scroll View using script in unity

Time:02-08

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
        }
    }
}

CodePudding user response:

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;
        }
    }
}

CodePudding user response:

  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

  •  Tags:  
  • Related