- Home /
if statement not working when detecting collision between two prefabs
I have a prefab in my game with the tag "Enemy". I want their positions to be added to a list of vectors when a circle collider on a child object of the prefab detects a collision. Here is my code:
public void OnCollisionEnter2D(Collision2D other){ if(other.gameObject.tag == "Enemy"){ vectors.Add(other.transform.position); Debug.Log("Enemy has entered range"); } } public void OnCollisionExit2D(Collision2D other) { if(other.gameObject.tag == "Enemy"){ vectors.Remove(other.transform.position); Debug.Log("Enemy has left range"); } }
The code does detect collisions correctly, as if i take the debug.log line out of the if statement it detects collision with my player's circle collider. However the if statement does not seem to run. Additionally, the colliders with the tag "Enemy" are not triggers and should be detectable. Please leave any ideas or suggestions, thanks.
Answer by hopper · Jul 21, 2020 at 08:24 PM
This might not be the best solution to what you want to do. It will only add the position for where it enters the Collider2D and then it will try to remove the position when it leaves the Collider2D. If the position changes by even a little bit, the Remove() method will not be able to remember it, and since Vector values are floats, if your enemy enters at (5.054, 10.671) and leaves at (5.053, 10.71), the Remove() method will be unable to delete this object from the list because it will not think it is there.
One way I would recommend fixing this is by not creating an array of Vector3's like it appears you have done here, but rather an array of Transform objects. Then if you want to find a specific enemy that is within your Collider2D, just call the following:
Transform[] enemies;
int enemyID = 0;
Vector3 positionOfEnemy = enemies[enemyID].position;
Debug.log(positionOfEnemy.ToString());
Or if you want to sort through and print the position of each enemy in the collider at any given time, you can use this: Transform[] enemies;
for(int i = 0; i < enemies.Length; i++)
{
Debug.Log("Enemy #" + i + " position: " + enemies[i].position.ToString());
}
So if you have 5 enemies this should print out:
Enemy #0 position: (0, 1)
Enemy #1 position: (0, 2)
Enemy #2 position: (1, 1)
Enemy #3 position: (1, 2)
Enemy #4 position: (1, 3)
//NOTE: WILL NOT AUTO PUT THEM IN ORDER, JUST WAS RUNNING OUT OF TIME