在开始时,对象会将链接添加到列表中。然后当我点击这个对象时,我需要得到这个对象的索引引用。怎么做? 我需要的小例子:
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);
}
答案 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
也可用于此目的。这个答案是为了让您了解如何自己做,以便您将来可以解决类似的问题。