How to find index of colliding Game Object in OnCo

2019-09-12 06:52发布

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

3条回答
何必那么认真
2楼-- · 2019-09-12 07:48

Try to use one parent for all your bad guys.

查看更多
混吃等死
3楼-- · 2019-09-12 07:51

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.

查看更多
倾城 Initia
4楼-- · 2019-09-12 07:51

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

查看更多
登录 后发表回答