如何在OnCollisionEnter2D()中找到冲突的游戏对象的索引 [英] How to find index of colliding Game Object in OnCollisionEnter2D()

查看:236
本文介绍了如何在OnCollisionEnter2D()中找到冲突的游戏对象的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a prefab and instantiated it a number of times in a script that it attached to another game object as below.

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

}

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

Since all of the instantiated objects in the array have the same tag and game object, how can I find the index of the colliding object in the array?

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

推荐答案

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

You should be able to just loop and compare the GameObject like this:

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碰撞时将变量设置为true循环所有badguys,并找到值等于true的badguy的索引.

If this doesn't work then you could add a script to the badguys (i.e. BadGuyScript.cs) and inside of the script add a variable called bool hasCollided = false; then when the badguy collides set the variable to true and then loop all the badguys and find the index of the badguy that has the value equal to true.

这篇关于如何在OnCollisionEnter2D()中找到冲突的游戏对象的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆