Alternate Solution to Laser Hit Triggering

Tell me what you think of this for detecting and responding to laser collisions with enemies… I didnt add a rigidbody to the enemy, just a collider. Then in the projectile script I did:

private void OnTriggerEnter2D(Collider2D collision) {
	collision.gameObject.SendMessage("IHitYou", damage);
}

Then on the enemies script I created this method:

public void IHitYou(int Damage) {
	HitPoints -= Damage;

	if (HitPoints <= 0) {
		Destroy(gameObject);
	}
}

This allows the damage magnitude to be communicated by the projectile to whatever it hits. And only things that care about getting hit by it will take action (damage / destruction / etc.) I liked it cause the code seemed much smaller / simpler and easier to understand…

Thoughts?

This is putting the onus of collision handling on the projectile rather than the enemy, which is fine, either way will work. The only issue I see is that the Projectile::OnTriggerEnter2D is not checking what it hit. So when the Projectile hits the Shredder, it will attempt to send the message “IHitYou” to it, resulting in extra SendMessage’s being invoked.
As well I am not sure what the runtime cost of SendMessage is versus GetComponent() and then accessing the public member variable “damage”. Would be interested to find that out.

BTW: I agree that at this point, there is no need for the RigidBody2D to be attached to the Enemy since at this point in the lesson there is no need for it. It just seems extra right now, maybe it will be made use of in the near future.

While this will work for this lecture, you won’t be able to apply any type of special physics effects to the enemy ship when hit without a Rigidbody. For example, a ship being hit by a projectile could spin out of control and smash into a nearby ship causing it to take damage or blow up.