- Home /
 
Checking if a gameobject is at a specfic # in a list
I have a list and I'm trying to check if a gameobject is at a certain place in that list but I not sure how to check it .
 public List<GameObject> Buttons = new List<GameObject>();
 
 
 
 if (this.CompareTag ("Barracks") && this.gameObject == Buttons[2].gameObject) {
     
 //Some code            
 
 }
 
 
 
               Above just checks if the list[#].gameobject is the same type of gameobject as this gameobject but it doesnt check if its this specific gameobject. Thanks!!
Answer by KringleHeim · Jan 05, 2017 at 06:08 PM
"Above just checks if the list[#].gameobject is the same type of gameobject as this gameobject but it doesnt check if its this specific gameobject". No, it doesn't :) It check if it is the very same variable (unless it's a primitive type (int, float...), string etc). To see this, try something similar to my code here, where the other gameObject is of your choosing. Point is that although they are both of the base class, GameObject, the == operator returns false.
   GameObject thisOne;
     GameObject otherOne;
     void Start () {
         thisOne = this.gameObject;
         otherOne = GameObject.FindGameObjectWithTag("MainCamera");
         Debug.Log((thisOne == otherOne).ToString());
         Debug.Log(thisOne.GetType());
         Debug.Log(otherOne.GetType());
 
     }
 
              Answer by LK84 · Jan 04, 2017 at 10:34 PM
You want to get the index of the GameObject in the List? Use List.FindIndex https://msdn.microsoft.com/de-de/library/x1xzf2ca(v=vs.110).aspx
 int index =Buttons.FindIndex(x=>x==gameObject);
 
              Answer by KoenigX3 · Jan 05, 2017 at 10:26 AM
I think the operator '==' should work well in this situation, since it checks whether the two references (on the left and right side of the operator) refer to the same object.
Do you want to check if the gameobject (which has this script attached to it) is the same as the gameobject, which is in the Buttons list at the index of 2?
Then it should return 'true' if they are referring to the same object. How do you know that the code above checks the types? What is the problem with the code above?
Your answer
 
             Follow this Question
Related Questions
A node in a childnode? 1 Answer
Add and destroy instantiated gameobject in linkedlist C# 1 Answer
Enabled all gameobjects in array 1 Answer