- Home /
How do you execute Trigger-collider collision only in one gameobject?
I'm trying to deal with units (generated from the same prefab) dealing damage to each other on collisions. Each Unit has both a Collider2D and a trigger on the front, that deals damage to other units that enter it.
I drew a small image (with Paint, sorry) to better illustrate what I mean and want. Desired Outcome
The problem I am having is that when a collision occurs (one unit enters the trigger of the other), both units damage each other, meaning Unit 2 also deals damage to Unit 1.
I have seen that you can create a separate gameObject as a child of the unit and attach the trigger to this gameObject.
However, the number of units will be very high so if possible I don't want to double the number of gameObjects used by units.
Also, the amount of damage dealt is calculated from many other parameters from many other scripts on the units and doubling all those references doesn't look like an elegant solution.
Any Ideas? Thanks
Answer by Marioooo · Nov 20, 2019 at 08:05 PM
you can check if the collider you are hitting is a trigger...
void OnTriggerEnter2D(Collider2D col)
{
if (col.isTrigger)
{
Damage();
}
}
this lead to two situations:
1: hitted entity executes the onTriggerEnter2D and col IS TRIGGER (gets hitted by a head): hitted entity make damage to itself.
2: hitting executes the onTriggerEnter2D and the col is NOT a trigger (the head hits a body): ignore damage
hope it helps!
this way the hitted entity "damages itself"... what I mean by this is that the damage code will be executed IN the hitted entity.. this way is more performant
Does it stay more performant if the damage that is done is calculated by a complex formula using stats from both units?
Interesting, and just to be sure, if let's say two heads were to hit each other (trigger touching trigger) does that cause an OnTriggerEnter2D event?
as you can see this, it will. i didn't think about that hehe...
maybe you could take a look on Collider2D properties and look for some property that could identify the collider as a head, maybe collider type (box or circle)
of course most simple solution is to make two separate scripts and make the head a child of the body...
Your answer
Follow this Question
Related Questions
How can I detect a collision point, but allow player to pass through collider. 1 Answer
How to make work a collision when is invisible? 3 Answers
NPCs collide with collider but player does not 1 Answer
How to get collision point when using onTriggerEnter 5 Answers
Objects placed manually collide, but don't if instantiated? 1 Answer