How can I check to see if a specific string is inside an array

I tried searching a bit for this but the phrasing makes it a difficult search. I’m looking for the unity way to simply do this:

var physics_objects = ["some_prefab_2", "some_prefab_7", "some_prefab_8"];

if ("some_prefab_2" in physics_objects) {
    do_something_with_physics("some_prefab_2");
}

What is the approprate way to do this in Unity. The “in” operator doesn’t seem to work from Javascript. Thanks!

EDIT: I would like to avoid looping through an array of strings if possible unless there is no built in method that would be more efficient.

Use a for loop, check each value in the array to see if it is equal to your string. for (int i = 0, i < physics_objects.length, i++){ if (physics_objects == "some_prefab_2"){ do something; } }

Sorry - I meant to add that to my original question. I'm trying to avoid looping for obvious reasons unless there is no built in method that would be faster. Thanks

ah I see, I will convert my answer to a comment so this question gets more attention.

1 Answer

1

The way to check the contents of your array:

if(Array.IndexOf(physics_objects, "some_prefab_2") > -1)
// Do something

BCE0019: 'IndexOf' is not a member of 'Array'. Am I missing something?

Make sure you're "using System;" It should be there - so I'm not sure. Try also Unity's built-in one which is: ArrayUtility.IndexOf(array, string); You can only use this for scripts inside Assets/Editor and you have to import: using UnityEditor; One final thought: You didn't try this did you: physics_objects.IndexOf Because that's not right - it's actually Array.IndexOf.

Are you "using System;"? ps, here is some conversation on which is faster http://answers.unity3d.com/questions/54106/how-fast-is-systemarrayindexof-on-iphone.html

That question has a IndexOf inside of a loop and as compared to using direct item access to edit the property of a member outside the loop (thus looping twice vs looping once.) This is a different scenario since IndexOf is going to loop the same way a manual loop would.

i see, thanks.