- Home /
instantiate in foreach loop only gives last string in list
i have a list and foreach string in the list i want a prefab with its child displaying the string. but it only displays one prefab with the last string in the list
itemDisplayPrefabclone=Instantiate(itemDisplayPrefab) as GameObject;
itemDisplayPrefabclone.transform.SetParent(displayParent.transform, false);
foreach (string testvariable2 in SavefileNames2)
{
Debug.Log(testvariable2); // displays all strings in list perfectly
itemDisplayPrefabclone.transform.GetChild(1).GetComponentInChildren<Text>().text = testvariable2;
}
Comment
Best Answer
Answer by Winterblood · Apr 19, 2016 at 10:09 AM
You are instantiating a single object before you begin the loop, and assigning all the names in the list to the same object one at a time. Put the first two lines inside the foreach loop and it should work.
Answer by aditya · Apr 19, 2016 at 10:18 AM
try this
foreach (string testvariable2 in SavefileNames2)
{
Debug.Log(testvariable2); // displays all strings in list perfectly
string tempText = testvariable2;
itemDisplayPrefabclone.transform.GetChild(1).GetComponentInChildren<Text>().text = tempText;
}
if testvariable2
is a Text
then Text tempText = textvariable2;
Your answer
Follow this Question
Related Questions
How can I do a foreach loop for an array of booleans? 1 Answer
Guarantee loop order of child objects. 1 Answer
foreach Gameobject in array problems 1 Answer
Making an AI Flee 2 Answers
More loop problems 1 Answer