- Home /
Not able to make a foreach loop
Hey
I'm trying to make a "lives left" functionality for my game, you know, the standard 3 lives in the right corner of the screen.
Thing is though, every time i try to make a foreach loop i get an error thrown in my face:
error CS1579: foreach statement cannot operate on variables of type `int' because it does not contain a definition for `GetEnumerator' or is not accessible
The code i'm using is looking like this:
using UnityEngine;
using System.Collections;
public class UserInterface : MonoBehaviour {
public int livesleft = 3;
void OnGUI(){
GUILayout.BeginArea(new Rect(Screen.width - 170,20,50,170));
foreach(int i in livesleft){
Debug.Log("i dont work");
}
GUILayout.EndArea();
}
}
The error is not only limited to the OnGUI function, it doesnt work in update either.
I'm about to go flip a table over this, because i have no idea what im doing wrong.
what you're looking for there champ is
for ( var count:int=0; count<livesleft; ++count ) doSomething();
when I gotta make objective-c, I always build up a macro
doThis$$anonymous$$anyTimes( n )
in this example you would simply say
doThis$$anonymous$$anyTimes( livesleft )
I$$anonymous$$O this is the most-needed control structure that is commonly missing from program$$anonymous$$g languages!
It's annoying that most languages contain toss like "switch()" that are crap and if anything you should avoid, but they don't have a simple "doThis$$anonymous$$anyTimes" structure ... bearing in $$anonymous$$d that, say, 50% of the time when you use "for..." you're actually just doing a "doThis$$anonymous$$anyTimes()" structure.
This concludes today's language gripes interlude.
Answer by nicloay · Aug 30, 2012 at 09:45 AM
livesleft must be an some type of array which implement IEnumerator Interface, not an a primitive like an int,
in your case you can use following construction
while ( --livesleft >0){
Debug.Log("blalblalbla");
}
Answer by Kryptos · Aug 30, 2012 at 11:36 AM
The foreach statement is used to iterate through a collection that implements the IEnumerable interface. You cannot use it with other types.
Here you can learn how the foreach loop works:
Your answer
Follow this Question
Related Questions
OnGUI button created by a foreach loop 4 Answers
Guarantee loop order of child objects. 1 Answer
Error assigning to a variable 0 Answers
Random NullReferenceException 0 Answers
foreach Gameobject in array problems 1 Answer