1

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")
1
  • you can use lambda Expressions for that Commented Nov 8, 2015 at 10:49

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.