To answer your question:
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
const int SEARCHED_INTEGER = 2;
int[] _Integers;
void Start ()
{
_Integers = new int[]{1,2,2,3,4};
int numberOfSearchedInts = 0;
foreach (int integer in _Integers)
{
if (integer == SEARCHED_INTEGER)
{
numberOfSearchedInts ++;
}
}
Debug.Log ("We found " + numberOfSearchedInts + " occurrences of the number " + SEARCHED_INTEGER + " in the array" );
}
}
Beading your question made me want to clear up a few things too though :
You’re right. The “int value1 = 1;” you declare in the beginning of your class is indeed a “field” or a “class variable” and the “int value1” inside the foreach is just another variable with the same name but it’s a different one and only accessible inside the loop.
I also would like to make sure you really understand what happens in a foreach-loop, since even if what you’re trying to do with “value1” was possible scope- and access-wise, assigning the value “1” to it wouldn’t accomplish anything
In a foreach, on each cycle, the variable you declare (value1) gets assigned the next value in the array you’re looping through. If you think about the meaning of “for each”, it really is misleading because you could think it’s something you can use to do something e.g. “for each (blueWhale in allWhalesArray)”, but foreach doesn’t provide any kind of filtering of content by itself. All it does is pull out values/references from the array and assign them conveniently for you in the variable you made.
Also remember that an int is a value type, so in your example if you assigned a different number to “value1” inside the foreach, the assigning doesn’t change the value inside the array, it only changes the value of “value1”.
If we are dealing with non-value types, it’s different
GameObject[] _GameObjects = new GameObject[]{new GameObject(), new GameObject(), new GameObject()};
foreach (GameObject gobj in _GameObjects)
{
// NOTE: GameObject is not a value type -> gobj is an actual reference to stuff inside the array
// changing "gobj" really changes things inside the array.
gobj.transform.position = Vector3.one;
}