Grab a specific item from a list


This is what I’m looking for:

public List<GameObject> objects = new List<GameObject>();


void Check()
   if(objects.Count() == 1)
     GameObject obj = //THAT ONE OBJECT

How would you solve this? :slight_smile:

Original post:

I have a list of selected GameObjects in my game, which I iterate through when assigning objectives etc. However, there are one objective that can only be done if only one object is selected. This is easily checked with the list.Count and so on. But if that returns “1”, meaning that only one object is selected - I want to assign the objective to it. However, I have previously used a foreach-loop to skim through the objects and assigning their objective… this is of course working even when the list only contains one object, but is there an easier way to access a particular object? From what I can see, I can get the index value of certain objects, but I don’t see a method where I can use that information to access the specific item.

The method will never run if the list.Count returns anything else than “1”. So I want to say, okay, then grab that item and tell it to do this…etc…

Thoughts? :slight_smile:

Try using a Linq Query.

Edit: I guess I don’t really understand the question. If you have 1 object in the list, you can still retrieve it by index.

if(objects.Count() == 1)
    GameObject obj = objects[0];

You can use IndexOf to find the index of a specific object in the list…

int index = objects.IndexOf(someKnownObjectReference);

And then use that index to grab the object…

if (index >= 0)
    GameObject o = objects[index];

But… if you already have a reference to the object (which you indicated was known) then there’s no need to find it in the list to modify it? Just modify the reference you already have… I’m not entirely sure what you’re trying to accomplish either, and the code doesn’t help me much. What is “that one object” referring to?

All these are crazy complex if you just want to find a certain item using a random number.
Let’s say you wanna find a name in this list;

List names = new List();

//You use a random int like so
int finder = Random.Range(0, 4);
//Then you just use this;
nameDisplayString = names[finder];