problem with loading list of strings on buttons
This might be a noob question, but I cant figure this out. I have a canvas with 5 buttons and I am trying to load a list of strings (names) on those buttons. It is quite easy to change the text of each button to particular name, where I am lost is how to load all five names on these five buttons. Here is a code >
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class ListLearning : MonoBehaviour {
List <string> names = new List <string>();
public GameObject parentCanvas;
// Use this for initialization
void Start () {
names.Add ("Wayne");
names.Add ("Phil");
names.Add ("Chris");
names.Add ("Memphis");
names.Add ("Adnan");
Debug.Log (names);
AddText ();
}
void AddText () {
foreach (Text t in parentCanvas.GetComponentsInChildren<Text>())
{
t.text = names[1]; // this works, each text is "Phil"
// t.text = names; //Why doesnt this load the whole list on buttons?
}
}
}
I have tried several other approaches but I really dont know how to do this ...any help guys? Thanks in advance
Answer by fvangeirt · Oct 05, 2015 at 09:24 PM
void AddText()
{
int i = 0;
foreach (Text t in parentCanvas.GetComponentsInChildren<Text>())
{
t.text = names[i];
i++;
}
}
Answer by SamPav · Oct 05, 2015 at 09:45 PM
Thanks a lot, that works! Although I have no idea why :D Even without explanation, that was very helpful, thanks again :) @fvangeirt
t.text is a string. names is a list of string. You can not assign a list to a single string variable.
What I do is: Via the foreach you loop over the text strings of your buttons. Parallel you loop with the integer i over the other list of strings to assign.
Sorry, can not explain it better. What exactly do you not understand?
Hm I guess I get it now. I am fairly new to scripting and I have not seen the i++ outside of forloop so that was confusing. Thanks a lot :)