- Home /
How to find index of colliding Game Object in 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
}
}
Answer by thereisnotrying · Apr 19, 2016 at 02:46 AM
I don't think you can. It is the list that references GameObjects not the other way around. So having a reference of that GameObject does not let you reveal any information hold by the list.
However, you could add an int variable "creation number" cn. This would require a script.
for (int i = 0; i < numberOfBadGuys; i++) {
GameObject badGuyObject = (GameObject)Instantiate(badGuy, new Vector3(Screen.width*i/2, Screen.height*i/6, camera.nearClipPlane ), Quaternion.identity );
//new line
badGuyObject.GetComponent<YourScript>().cn = i;
badGuys.Add(badGuyObject);
}
So later you could access it later:
if (col.gameObject.tag == "badGuy") {
// how can I tell the index of colliding game object in badGuys array
int index = col.gameObject.GetComponent<YourScript>().cn;
}
If you want this index to interact with your bad guys objects to take away health or perform other operations remember that you already have access to the object itself. So if this would be collision script for a rocket flying into bad guys you could just code something like this:
if (col.gameObject.tag == "badGuy") {
col.gameObject.GetComponent<YourScript>().HitByRocket():
}
Answer by jgodfrey · Apr 18, 2016 at 10:20 PM
Compare the id InstanceID of the collided object to the InstanceID's of the cached objects until you find a match?
http://docs.unity3d.com/ScriptReference/Object.GetInstanceID.html