If element exists in array do...

Hello!I am pretty new to the arrays and i couldn’t find a way to see if a number is included in an array of numbers except for using a “for” loop.Is there a lighter way of doing that,like a single command?

Hi!, maybe this can help?, you can print or Debug.Log an array length :

var myArray = new Array(2); //two items

myArray[0] = "Item 0";
myArray[1] = "Item 1";

Debug.Log(myArray.length);

that will return 2, if you have two items... and so.

There is nothing built into standard arrays that will do this. You have a few options…

  1. Research searching algorithms and implement one in your code that you can use.
  2. Use the c# Generic class called List. This has a built in function called “Contains” that will return true if the given element exists in the list. List operates just like an array, but with many added benefits. See: List<T> Class (System.Collections.Generic) | Microsoft Learn
    Just include the namespace of System.Collections.Generic and you will have access to the list class.
using System.Collections.Generic
List<int> intList = new List<int>();

Personally, I would use a List, as its benefits often out-weigh the slightly larger performance expense vs a standard array.

You have to loop.

function IsInArray(element : int, arr : int[]) : boolean
{
      for(i = 0; i < arr.length; i++)
      {
            if(element == arr[i])
                return true;
      }
      return false;
}

Do you have some huge array for which you are worried it would take too long? If your array is sorted you can do better or if the array has only unique elements and you can flag them when you put them in the array, but in general you have to go through each one and check.

Ahhhh…

for this exact reason, when it best suits… I use ArrayList… It compares objects and has an IndexOf method

If(arrayList.IndexOf(hit.transform.gameObjct) == -1) arrayList.Add(hit.transform.gameObjct);

Hello Ted,

This is one way to do it :

List numbers = new List();
numbers.Add(0);
numbers.Add(10);
numbers.Add(25);

bool isNumberPresent = numbers.IndexOf(10) >= 0;

This is even faster :

HashSet numbers = new HashSet();
numbers.Add(0);
numbers.Add(10);
numbers.Add(25);

bool isNumberPresent = numbers.Contains(10);

If the set of numbers fall within a relatively reasonable range, such as 0 to 999, then the following method is the fastest :

bool[ ] numbers = new bool[1000];
numbers[0] = true;
numbers[10] = true;
numbers[25] = true;

bool isNumberPresent = numbers[10];

Hope this helps!

El Diablo

You probably don’t want to use ArrayList and could be better suited with List for a few reasons.

  1. It can give you the objects in the lowest common format, transformList will return a Transform object, rather than ArrayLists System.Object return that must be casted.
    2) This conversion can require objects needing to be boxed, adding additional overhead to accessing and adding of objects.
    3) The danger of being able to insert a boolean (or other incorrect object) into a list of Components can create such monstrous headaches in the future (The best way to only allow only usable types into your collection is to make sure the compiler enforces it).
    You can use a base type such as List or List to put all sorts of things in components and still access their shared variables and methods.

Actually there is a built in way. Put this at the top of your script:

using System.Linq;

and then you can do this:

if(myArray.Contains(7)) { DoWhatever… }

Actually, to the original poster, and all the people saying there’s no way to do these things and posting convoluted workarounds, I highly suggest reading about Linq, it will make all your coding lives much easier. :wink:

1 Like

LINQ is definitely doable, but I wouldn’t recommend it in general (especially to beginner programmers) since there are hidden performance implications that even veterans are unaware of. LINQ can definitely make life easier, but it will rarely make your code perform faster, and in most cases it’s slower (not because LINQ is inherently flawed, rather because most people don’t really understand how it’s really interacting with the data structure).

I’d actually completely disagree. Beginner programmers get a lot more out of simple and easy to understand code than they get out of eeking an extra nanosecond out of custom code… especially since if they’re beginners or just pasting things that random people on the internet tell them to, it’s very likely that the custom code actually isn’t faster. I’m not positive but I’d bet money that using array.Contains() is more performant than all the other recommendations in this thread. And unless he’s repeatedly trying to look through a huge array thousands of times per second, it’s really not going to make any noticeable difference.

even faster than this? :slight_smile:

it won’t be faster than looping through the array either.

The problem with your solution ivkoni is that it requires that the values be integers… This will not help if all the objects need to be strings or GameObjects.

Lol, well that’s a very specific case. Seriously though, I’ve seen way too many new (and old!) programmers spend days wasting their time doing convoluted stuff because they’re convinced that they can make their method work faster than Microsoft’s (or Sun’s, or Boost’s, or whoever) and 90% of the time they’re wrong, and the other 10% of the time, it doesn’t even matter anyway because all of their slowdown is completely unrelated to whatever they’re messing with. Unless you’re absolutely positive that you are outsmarting the people who developed the language you’re writing in (and if you’re a beginner, you’re not), then it’s way better to spend your time writing your game as simply and clearly as possible, then, AFTER you get most of it working, use a profiler and investigate any parts that are specifically causing a lot of slowdown and optimize those pieces only.

it is Diabolo’s solution, but it could be made to work with anything, since you can create a class and have the index of the object as a variable, then when you put the object on the array, you update the “IsInArray” array based on that index. Or you can have a boolean in the class - “isInArray” that you set directly, if your objects are considered unique…

Also, I want to say that if a noob programmer asks “How do I search this array for a thing”, that replying “OMG arrays suck you should use Lists or something else instead” is definitely not helpful. It’s confusing a noob programmer, tricking him into stressing out that he has to go back and redesign all his code because he did something “wrong”, when really his code is absolutely fine and going back to change it is going to make absolutely zero noticable performance difference. If someone wants to search an array for something, show them how to search an array for something, and then, if you must, you can digress into how you’re pretty sure you know a secret way to do it slightly faster if he spends the next three days restructuring all his code from the ground up. :wink:

I think you guys are over-thinking matters a bit. The Collections methods like Contains() and IndexOf() are iterating over the values in the List anyway - so it’s not a huge gain over just doing your run of the mill foreach loop. One is just more verbose than the other. (And I would think the loop with a builtin array would end up being faster ultimately.)

Hehehe - ye of little faith.

If you can identity the GO’s before hand - e.g. give em all names - then simply use enum to translate the names into integers and voila - it works :stuck_out_tongue:

//not tested, probably doesn't work as is.

enum Unit {GoodGuy, WingMan1, WingMan2, WingMan3, BasicBadGuy1, UpgradedBadGuy2, BigBoss3};

Unit unitType =Unit.WingMan1;

bool[] unitArray = bool[7];

void OnSave()
{
unitArray((int)unitType) = true;
}

I’d just use a list myself, but you can always be a bit crazy!

Thank you very much guys for your help and anwsers!Yes,baisically i was wondering if there is a shorter or even faster way of checking if var x : float can be found inside an array of numbers,even if the array doesen’t really respect a math algorithm or anything (ex.: 1,34,764,21,55,6651,5415,77,4,553).I am thinking that it has anyway to process something like a for loop to check all the elements,but i was wondering if there is a shorter way to write it,like array.ElementInArray(X); - [no,that’s not actually a command :smile:].

Thanks alot!ArrayLists and Linq did the job :smile: I wasn’t that much into C# so i didn’t knew to much about them :slight_smile:

P.S.:I would have replied yesterday evening but exacly when i hit “Post Quick Reply” my internet broke down :expressionless: I Only managed to copy-paste this message

ShirtNum--;
        if(ShirtNum < 0)
        {
            ShirtNum = Shirts.Length - 1;
        }
        if (!UserData.OwnedShirts.Contains(ShirtNum))
        {
            ShirtNum--;
            if(ShirtNum < 0)
            {
                ShirtNum = TotalShirts.Length - 1;
            }
        }

I’m a relatively new coder and I need help with the !UserData.OwnedShirts.Contains(ShirtNum) part, as I need a way to see if the OwnedShirts array contains the selected shirt (ShirtNum) I’ve tried some of the other things listed above, but I’m having a hard time finding one that works Could y’all help me (and maybe find a way for me to do the if statement over again & again until it lands on a shirt I own?)

You can add using System; to the top of the file and then use Array.IndexOf. It returns -1 if the array did not contain the item:

if(Array.IndexOf(UserData.OwnedShirts, ShirtNum) == -1)

Alternatively you could use a List<int> instead of an int[ ] for OwnedShirts, since that has a Contains method.

There’s also HashSet<T>, which would be a good choice in that it can’t contain any duplicates, and has a very optimized Contains method. However, Unity can’t serialize it or visualize it in the Inspector, so unless you fill the collection with items programmatically, using List<T> would be simpler :slight_smile:

1 Like