【问题标题】:How i can get GameObject index in the list?我如何在列表中获取 GameObject 索引?
【发布时间】:2018-03-16 09:44:30
【问题描述】:

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

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

【问题讨论】:

  • 有什么代码要分享吗?

标签: c# list unity3d gameobject


【解决方案1】:

遍历Objects 列表。检查它是否与单击的游戏对象匹配。点击的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 也可以用于此。这个答案是为了让您了解如何自己做,以便您将来可以解决类似的问题。

【讨论】:

  • @ChristopherHarris 是的,我知道。在 Unity 中,您将需要做这样的事情,有时,内置功能不可用。我想向 OP 展示如何做到这一点,以便 OP 可以将其应用于他/她可能的下一个问题。例如,昨天问的this 非常相似,但没有内置函数来处理它。这是相同的技术,但 Objects.IndexOf 不会解决它。
  • 除了也有内置函数。我继续并为该答案提供了替代方案。
  • 我不明白,有一个用于检索列表中的项目的内置函数。为什么要重新发明一个运转良好的轮子?还是我们都在这里遗漏了什么?我明白你解释了这个概念,但你也应该说它归结为 list.IndexOf(reference);
  • 因为有些人喜欢写代码而不是用它做东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 2015-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
相关资源
最近更新 更多