Like @CodeSmile said, if you need the index, use a for loop instead.
Pro Tip: in Visual Studio, itâs very easy to convert a foreach loop to a for loop (and vice versa), just put your text cursor on the âforeachâ keyword, hit Alt+Enter (or Ctrl+.) to open suggestions menu, and there youâll find âConvert to âforââ
Now if you insist using a foreach, and if youâre iterating a List, you could always get the index of an item by using var index = myList.IndexOf(item); but it will do a search (a for loop) to find your item index⌠so basically youâre doing a nested for loop for no reasonâŚ
If I only had a dollar for every foreach() that I ended up refactoring as a for() loop!
foreach() is âcute,â sorta in the ballpark of âkinda nice if it works for you.â
If it helps, think of foreach() as more the domain of opaque set / collections operations done by compsci teachers: simple example set operations involving absolutely nothing else of relevance regarding the collection or any other collection.
But a good old for() is where the actual meat and potatoes work gets done, especially in agile complex tightly-bound gamedev coding. You almost always end up needing to know offsets and indices, even in managed code land, just because often there is an importance to ordering or numbering that simply doesnât exist to the theoreticians scribbling on the blackboards.
Keep these two tools in mind and be ready to swap effortlessly between the two of them.
Remember: underneath it all, itâs just a code loop controlled by something.
OP could be going through a linkedlist, where using L is an expensive O(n). Sure, one could rewrite as a FOR and manually create and move the iterator, with i=i.next(); and so on, but that still wouldnât get the index.
You can do it with the following code just be aware that it will be slower because itâs now going to have to search through the array or list to find the index you could have been tracking with a for loop.
var index = Array.IndexOf(PlayerController.instance.availableGuns, theWeapon);
Hereâs the variant for Lists.
var index = List.IndexOf(PlayerController.instance.availableGuns, theWeapon);
Meanwhile hereâs your code using a for loop (change Length to Count for a List).
for (var index = 0; index < PlayerController.instance.availableGuns.Length; index++)
{
if (theWeapon.weaponName == PlayerController.instance.availableGuns[index].weaponName)
{
hasWeapon = true;
print("hasWeapon = " + hasWeapon);
PlayerController.instance.availableGuns[index].baseWeaponPower += 10;
}
else
{
print("hasWeapon = " + hasWeapon);
}
}
Maybe but itâs very uncommon to see anyone using the LinkedList type as itâs almost never touched on in tutorials.
Generally I use foreach only when itâs not possible to use a for loop (IEnumerable). In all other cases (indexable collections), I use a for by default. As a (tiny) bonus: for loops are significantly faster than foreach in Lists.