Delegate or Event: Reacting to another object's collision functions

Hey, folks!

I’m new to the fancier aspects of C#. I’m trying to figure out when to use Events instead of delegates.

I have a character who swings around a sword with a hitbox attached to it. When the hitbox collides with something, I want the character class to do the damage computations.

I currently have this working by firing off a delegate from the weapon-hitbox’s OnTriggerEnter function. When the character class wakes up, they just add a function to the hitbox’s trigger-enter delegate.

I haven’t worked much with events. Would I have been better off with events?


The hitbox currently has the following code:

 public delegate void OnTriggerEnterDelegate(Collider Other);
 public OnTriggerEnterDelegate OnTriggerEnterSteps;
 	
 void OnTriggerEnter(Collider Other){		
       if(OnTriggerEnterSteps!=null){
	         OnTriggerEnterSteps(Other);	
       }
 }

The character code then assigns the damage function like so:

WeaponHitBox.OnTriggerEnterSteps+=MeleeStrikeTarget;

You don’t need to define your own delegate for this. C#'s System namespace already has an appropriate one created for you: Action. You’re probably never going to have to define your own delegates.

Do not use PascalCase for fields. PascalCase would be used for properties, or events, which have similarities to properties behind the scenes.
Do not use public fields.
There is generally no reason to have public delegates; definitely use events for better encapsulation.

Your system doesn’t sound great, to me, but given what you have, here’s what you’d want to change to:

public event Action<Collider> OnTriggerEnterSteps;

The rest of the code could stay the same.

If I understand this page correctly, I don’t have enough rep to close my own question.

Please close it if you get the chance.