简体   繁体   中英

Get index from array comparing a property of each index in the array

Can I do this?

Array.IndexOf(Array, (index.propery == true))

Where index equals IndexOf's own incrementer.

Why I'm asking :
I'm using Unity, I have a number of objects which are components of a larger, or whole, object in the game. I want to use Unity's editor to assign these Objects to their variables in the game. I later need to iterate over these objects. I would like to do this by having them in an array (as unity can still edit these). The problem begins where in an array I cant access the objects with a meaning-full index. I would like to refer to the components by name, a dictionary is not accessible to by Unity (and incurres a performance overhead).

My solution, which I'm asking whether is possible is to access the array index by searching for it with IndexOf(), but can I do it by searching with the name of the GameObject at each index?

GameObject result = Array.IndexOf(GOArray, GOArray[INDEX].gameObject.name == "theoneiwant")

You have Array.Find:

GameObject result = Array.Find(GOArray, g => g.name == "theoneiwant");

Just pay attention it is not very efficient. If you want speed, you best use dictionary, maybe pre-build your dictionary from an array on startup.

try this for getting index

var index = Array.FindIndex(yourArray, gameobj => gameobj.propery == true);  

UPDATE
OK maybe i didn't understand your question very well.

  • If your GameObjects have unique names you can simply find them by their name, it's fast and reliable:

     public GameObject targetObj; targetObj = GameObject.Find("objectname"); 
  • but if they haven't you can create a List of GameObjects, assign your gameObjects to it and then search through them with this code:

     public List<GameObject> myObjList = new List<GameObject>(); public GameObject targetObj; targetObj= myObjList.Where(x => x.name == "objectname").SingleOrDefault(); 

use name or any attribute you want to find them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM