我如何在列表中获取GameObject索引?

时间:2018-03-16 09:44:31

标签: c# list unity3d gameobject

在开始时,对象会将链接添加到列表中。然后当我点击这个对象时,我需要得到这个对象的索引引用。怎么做? 我需要的小例子:

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脚本:

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

1 个答案:

答案 0 :(得分:1)

循环遍历Objects列表。检查它是否与单击的GameObject匹配。单击的GameObject可以在OnMouseDown函数中使用gameObject属性获取。如果它们匹配,则从该循环返回当前索引。如果它们不匹配,请将 -1 作为错误代码返回。

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;
}

这应该有效,但最好停止使用OnMouseDown功能,而是使用OnPointerClick功能。

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;
    }
}

有关OnPointerClick的详细信息,请参阅this帖子。

修改

Objects.IndexOf也可用于此目的。这个答案是为了让您了解如何自己做,以便您将来可以解决类似的问题。