Search code examples
c#listunity-game-enginegameobject

How i can get GameObject index in the list?


At the start, the object adds a link to it to the list. Then when i click on this object, i need to get index reference of this object. How to do it? Little example what i need:

public static List<GameObject> myObjects = new List<GameObject> ();
public GameObject ObjectA; //this is prefab
void Start(){
    for (int i = 0; i < 10; i++) {
        GameObject ObjectACopy = Instantiate (ObjectA);
        myObjects.Add (ObjectACopy);
    }
}   

ObjectA script:

void OnMouseDown(){
    Debug.Log(//Here i need to return index of this clicked object from the list);
}

Solution

  • Loop through the Objects List. Check if it matches with the GameObject that is clicked. The GameObject that is clicked can be obtained in the OnMouseDown function with the gameObject property. If they match, return the current index from that loop. If they don't match, return -1 as an error code.

    void OnMouseDown()
    {
        int index = GameObjectToIndex(gameObject);
        Debug.Log(index);
    }
    
    int GameObjectToIndex(GameObject targetObj)
    {
        //Loop through GameObjects
        for (int i = 0; i < Objects.Count; i++)
        {
            //Check if GameObject is in the List
            if (Objects[i] == targetObj)
            {
                //It is. Return the current index
                return i;
            }
        }
        //It is not in the List. Return -1
        return -1;
    }
    

    This should work but it is better that you stop using the OnMouseDown function and instead use the OnPointerClick functions.

    public class Test : MonoBehaviour, IPointerClickHandler
    {
        public static List<GameObject> Objects = new List<GameObject>();
    
        public void OnPointerClick(PointerEventData eventData)
        {
            GameObject clickedObj = eventData.pointerCurrentRaycast.gameObject;
    
            int index = GameObjectToIndex(clickedObj);
            Debug.Log(index);
        }
    
        int GameObjectToIndex(GameObject targetObj)
        {
            //Loop through GameObjects
            for (int i = 0; i < Objects.Count; i++)
            {
                //Check if GameObject is in the List
                if (Objects[i] == targetObj)
                {
                    //It is. Return the current index
                    return i;
                }
            }
            //It is not in the List. Return -1
            return -1;
        }
    }
    

    See this post for more information on OnPointerClick.

    EDIT:

    Objects.IndexOf can also be used for this. This answer is here to make you understand how to do it yourself so that you can solve similar issues in the future.