Assigning multiple GameObjects to Variables using Array of Strings

I’m trying to assign multiple GameObjects to variables using an array with foreach loop instead of assigning them line by line.

string[] names = {"NameA", "NameB", "NameC", "NameD", "NameE"};

foreach (string name in names) {
    name = GameObject.Find(name);
}

This code throws error CS1656 Cannot assign to ‘name’ because it is a ‘foreach iteration variable’

Anyone know how I can tell the script to use the string value stored in name instead of using the keyword name itself?

You should ask this in the scripting forum.

But essentially you’re modifying the ‘name’ variable from the foreach(string name in names). Can’t do that.

string[] names = {"NameA", "NameB", "NameC", "NameD", "NameE"};
List<GameObject> gameObjects = new();
    
 foreach (string name in names) {
        gameObjects.Add = GameObject.Find(name);
    }

Obviously I have not tested this and there’s no test for if GameObject.Find doesn’t find ‘name’

If you could use tags on your GameObjects it’s easier to find GameObjects using a tag.

Hope this helps.

what you want is called a dictionary<string,gameObject>

I don’t know what exactly you want to achieve. After a while with Unity, I’ve abandoned ideas like using Find. The Unity editor has a great solution when it comes to binding game objects, components and scripts (drag and drop in the inspector).

public List<GameObject> treesPrefabs;
public List<GameObject> trees;

void Start()
{
    trees.Add(Instantiate(treesPrefabs[Random.Range(0, treesPrefabs.Count)]));
}

Please provide more details on what you want to achieve.