- Home /
Detect multiple collisions with OnTriggerStay2d
Hey, i have a circle collider 2d that is set to trigger on my player. I have a script that checks if you touch an enemy. But even though its hitting both enemies, it only damages one, and when the enemie is dead, the other one. How can i detect and damage both?
You'll need to post the actual collision code for us to help. :-)
Answer by AnisimovArthur · Apr 28, 2019 at 12:22 PM
It would be great to see your collision code for the problem solving.
Hope this code helps you. You check a gameobject tag, if it is an enemy you damage it.
private void OnTriggerEnter2D(Collider2D collision)
{
bool isEnemy = collision.gameObject.CompareTag(enemyTag);
if (isEnemy)
{
collision.gameObject.GetComponent<Enemy>().hit();
}
}
Could this work with OnTriggerStay? I check if you click and then if you collide, it would take some precision to click right at the frame it enters ;)
Answer by Ryox92 · Apr 28, 2019 at 12:20 PM
Ok I think this should be helpful. Make sure you to use tag (Enemy) for all your enemies
EnemyScript[] enemies;
void Start()
{
enemies = FindObjectsOfType<EnemyScript>();
}
void OnTriggerEnter2D()
{
if (other.gameObject.CompareTag("Enemy"))
{
foreach (EnemyScript enemy in enemies)
{
//Your damage code
}
}
}
Is there any reason you want to use OnTriggerStay2D? To me It only makes sense to apply the damage when you enter the trigger for all enemies unless if you are doing something else.
Hope this helps :)
This would damage all enemies regardless of who was actually in the trigger -- which may be none, seeing as you're using a different means of deter$$anonymous$$ing enemies (Tag vs having an EnemyScript instance).