How to find index of colliding Game Object in OnCollisionEnter2D()

…衆ロ難τιáo~ 提交于 2019-12-12 02:53:23

问题


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

回答1:


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

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.




回答2:


Have you considered making your bad guys aware of their index?




回答3:


Try to use one parent for all your bad guys.



来源:https://stackoverflow.com/questions/36690789/how-to-find-index-of-colliding-game-object-in-oncollisionenter2d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!