- Home /
The question is answered, right answer was accepted
How do you find an Index of an Arrayed/Listed Object?
For example I have 5 Marbles and I want to find the 3rd Marble in my group.
Pretty Simple.
All I want to do is find out which Index is this GameObject in my group.
Such as.
public List<GameObject> Marbles;
print(Marbles[2].index);
But i'm pretty sure it isn't that simple haha.
If anyone can help me i'd appreciate it.
Answer by Garazbolg · Oct 07, 2015 at 02:25 PM
You can simply use the IndexOf() of List : https://msdn.microsoft.com/fr-fr/library/e4w08k17(v=vs.110).aspx
public int IndexOf( item);
In you case your case (if i understood well) you have a list and a gameObject and you want to now the index of this gameObject in the List.
public List Marbles; int index = Marbles.IndexOf(Marbles[2]) //index will be equal to 2
Thank you both for providing that link. I was honestly having a hard time understanding the IndexOf rule from the original site.
Anyways.
It worked just as perfect as ever. Now my Cards move from the position depending on their order position and what not, its great. Thanks Guys!
Answer by DiegoSLTS · Oct 07, 2015 at 02:21 PM
I don't get it, isn't the index "2"? You're just writing it there.
When you do "Marbles[2]" you get a GameObject reference, and GameObject doesn't have a member called "index".
If you already have an object reference and want to know the index where it can be found in a list there's the "IndexOf" method: https://msdn.microsoft.com/en-us/library/e4w08k17%28v=vs.110%29.aspx
Thanks for the reply!
$$anonymous$$hm yes that is true, but I am using a for loop function In my script.
Which Does this.
for(int i = 1; i < NumberOfCards; i++){
print(DeckCards[i].gameObject.name);
}
I want to be able to get the Card's order number, by getting it's index.
And then move it's position and other few things based on it's card order.
But i'll check out your link and see how it turns out.
Follow this Question
Related Questions
Searching a List of GameObjects by name 2 Answers
A node in a childnode? 1 Answer
Unity c# indexoutofrangeexception: array index is out of range 1 Answer
How to return index of List element? 1 Answer
How to find a Class by value 2 Answers