- Home /
How To Assign List Elements To Array Elements?
Hello, ive stumbled across an issue im not sure how to solve dealing with UI so I have a list of strings & an array of game objects that finds all UI gameobjects with a tag. what I need assistance with is how do I assign the first element of the list to the first element of the array & so on
public List<string> Names = new List<string>();
public GameObject[] bars;
public GameObject prefab, parent;
public int index;
void Start()
{
bars = GameObject.FindGameObjectsWithTag("Bar");
index = PlayerPrefs.GetInt("BarCount");
if(bars.Length < index)
{
//spawn certain number of bars (with names if possible)
for (int i = 0; i < index - 1; i++)
{
var bar = Instantiate(prefab);
bar.transform.SetParent(parent.transform, false);
}
}
for (int i = 0; PlayerPrefs.HasKey("SaveName" + i); i++)
{
Names.Add(PlayerPrefs.GetString("SaveName" + i).ToString());
}
}
here is where I want the elements to be assigned to each other in order then display the string element to the assigned bar. I have a vertical layout group spacing each bar.
Answer by elingranath01 · Jul 27, 2021 at 05:47 PM
As long as you make sure the array is the same length as the list, it's as simple as just making a for loop to assign the values from the list to the array.
for (int i = 0; i < array.Length; i++){
array[i] = list[i];
}
There is a much simple work around here....you just have to do
array = list.ToArray();
simple as this...
Yes, but GameDevH20 said they wanted to assign a list of strings to an array of gameobjects, not sure in what way they want to assign the list but I'm assu$$anonymous$$g they want to do gameObjectArray[i].name = nameList[i]; Seems like an odd way of assigning names when you can just do it in the inspector but I assume this is what GameDevH20 was wondering about
Answer by Campbell52 · Jul 28, 2021 at 10:15 AM
First, you can convert array to ArrayList using 'asList ()' method of ArrayList. Add an element to the ArrayList using the 'add' method. Convert the ArrayList back to the array using the 'toArray()' method.
Your answer
Follow this Question
Related Questions
C# ArrayList match to string? 1 Answer
How to check if the string is on a text file 0 Answers
images assigned to gameobjects by tag 2 Answers
How do I check for strings in an array to match up with the index of another array? 1 Answer
How can I instantiate parented ui objects above previously instantiated children? 1 Answer