如何在OnCollisionEnter2D()中找到碰撞游戏对象的索引

时间:2016-04-18 09:59:41

标签: unity3d unity5

我已经创建了一个预制件并在脚本中多次实例化它,它附加到另一个游戏对象,如下所示。

void Start () {

    badGuys= new List<GameObject> ();

    int numberOfBadGuys = 6;
    Camera camera = GameObject.FindGameObjectWithTag ("MainCamera").GetComponent<Camera> ();

    for (int i = 1; i < numberOfBadGuys + 1; i++) {
        GameObject badGuyObject =  (GameObject)Instantiate(badGuy, new Vector3(Screen.width*i/2, Screen.height*i/6, camera.nearClipPlane ), Quaternion.identity );
        badGuys.Add(badGuyObject);
    }

}

由于数组中的所有实例化对象都具有相同的标记和游戏对象,如何在数组中找到碰撞对象的索引?

void OnCollisionEnter2D(Collision2D col)    {
    Debug.Log("collision has began");

    if (col.gameObject.tag == "badGuy") {
             // how can I tell the index of colliding game object in badGuys array
      }
}

3 个答案:

答案 0 :(得分:1)

你有没有考虑让你的坏人知道他们的指数?

答案 1 :(得分:0)

您应该能够像这样循环并比较GameObject:

void OnCollisionEnter2D(Collision2D col)
{
    Debug.Log("collision has began");

    int collidedBadGuyIndex = -1; //This variable should be outside this function.

    if (col.gameObject.tag == "badGuy")
    {
        for (int i=0; i<badGuys.Length; i++)
        {
            if (col.gameObject.Equals(badGuys[i]))
            {
                collidedBadGuyIndex = i;
                break;
            }
        }
    }
}

如果这不起作用,那么您可以向badguys添加一个脚本(即BadGuyScript.cs),并在脚本内添加一个名为bool hasCollided = false;的变量,然后当badguy碰撞时将变量设置为{{1然后循环所有badguys并找到值为true的badguy的索引。

答案 2 :(得分:0)

尝试为所有坏人使用一个