- Home /
Check if an int is equal to an array int
i want to do something if my integer is equal to any element of an int array using this variables:
var myInt : int;
var myIntArray : int[];
Answer by MartinCA · Apr 09, 2013 at 08:39 PM
Just iterate over the entire array and exit with success as soon as you find a match, otherwise return no match is found. JS Arrays should also have this functionality built in.
Function FindInArray( needle : int, haystack : int[] ) : bool
{
for each ( var item : int in haystack )
{
If ( needle == item )
Return true;
}
Return false;
}
Mind you, this is pseudo JS, I am writing from my ipad and my knowledge of the syntax is kinda rusty - so don't expect a copy paste to work. But this should give you a general idea.
if(myIntArray.indexOf(myInt) > -1)
That's the usual way to do it in Web javascript - I imagine it'd be the same in Unity javascript.
Unity Javascript isn't at all like web Javascript though, which is why it's usually referred to as Unityscript. Also built-in arrays are part of $$anonymous$$ono, specifically System.Array. So anything to do with arrays (not the built-in Unity Array class, which shouldn't be used anyway) can be looked up in the $$anonymous$$SDN docs under System.Array. There's never any need to write your own code for basic functionality like this.
Answer by whebert · Apr 09, 2013 at 09:31 PM
Not sure if you are stuck using an array, but you could always use generic lists instead - gives you dynamic arrays and some easy to use functionality, including an easy way to see if the list contains something.
import System.Collections.Generic;
var myIntList : List.<int> = new List.<int>();
// Add your ints
myIntList.Add(1);
myIntList.Add(2);
myIntList.Add(3);
if(myIntList.Contains(myInt))
{
// The list contains your int
}
Answer by Eric5h5 · Apr 09, 2013 at 09:35 PM
Use IndexOf, which returns -1 if the item is not found.
if (System.Array.IndexOf (myIntArray, myInt) != -1) {
// it's here yo
}