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
}
}
Try to use one parent for all your bad guys.
You should be able to just loop and compare the GameObject like this:
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 totrue
and then loop all the badguys and find the index of the badguy that has the value equal totrue
.Have you considered making your bad guys aware of their index?