Not able to make a foreach loop


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");

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.

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){

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:

  1. foreach, in (C# Reference)
  2. C# Foreach (dotnetperls)