Need to start this topic.
here is my code
CopyCount = 1000;
InstanceList = new GameObject[CopyCount];
for (int i = 0; i < CopyCount; i++)
{
GameObject item = Instantiate(Cubic[Random.Range (1,14)]) as GameObject;
//item.transform.parent = transform;
InstanceList[i] = item;
InstanceList[i].transform.Translate(Random.Range(10,40),Random.Range(0,3), Random.Range (10,40));
rnd=Random.Range(1,6);
InstanceList[i].transform.Rotate(0,Random.Range (1,5)*90,0);
InstanceList[i].renderer.material=Mat[rnd];
}
How to make this code, using “Lists” with “Foreach”
Sorry for basic questions.
Well you can use a foreach on the array as it is like so:
foreach( GameObject o in InstanceList )
{
}
If you want a list you could use
InstanceList.ToList();
Whats wrong with your code as it is? A for loop is actually faster in some cases than a foreach loop.
(FOREACH Vs. FOR (C#) - CodeProject)
What is “o”? I need this example more for understanding than practically use in this case.
‘o’ is the temporary variable that will be created and assigned to be each element in the list sequentially. It’s equivalent to
for (int o; o < InstanceList.Count; o++)
{
InstanceList[o].doSomething();
}
As for speed, the bytecode compiler will be able to optimize pretty efficiently, to the point that any difference between for and foreach will be negligible in comparison to other processing tasks in your game loop. If you want to know more you might want to google for help with C# and foreach syntax/use.
o is the name of the variable used to store each GameObject as it loops through the array. You can use any name you want.
Karl
Foreach actually won’t work in this case because you’re trying to populate InstanceList, rather than trying to iterate over the existing entries in it.
You can use a list instead of an array though: instead of setting objects into particular slots, you’d use Add() to just add each new object to the end of the list.
1 Like
Lists are best used when you have no idea how many elements you need to store. Arrays should be used over lists when possible, because they are faster to search through.
Example of a good time to use a list:
An inventory where you can carry unlimited amounts of items, so long as they all weigh less than 300 pounds combined. (Could have 5000 items without weight, or 200 that weigh 1 pound, etc)
Example of a similar scenario that should use arrays:
A “grid” inventory system where each item can only occupy one slot. You have 32 slots, so you always know you can have a max of 32 items. You could still use a list, but using an array is more efficient in this case.
If the array has only one field, an array is best.
For 2 fields, a dictionary for key value pair lookups is the most efficient.
For anything else, I’d suggest generic lists.