Subscribing to event from external class

I have a central GameLogic module which is in charge of determining whether the player hits his opponent, and I’m trying to subscribe every enemy’s GotHit function to that event, so I only have to keep track of it in one place:

public class GameLogic : MonoBehaviour {
	public int damage = 1;
	public delegate void ComatEvent();
	public static event CombatEvent HitEnemy;
}

public class Enemy : MonoBehaviour{
	void OnEnable(){
		gameLogic.HitEnemy += GotHit (gameLogic.damage);
	}
	void OnDisable(){
		gameLogic.HitEnemy -= GotHit (gameLogic.damage);
	}
	void GotHit(int damage){
	}
}

However, this produces two errors: “GameLogic.HitEnemy cannot be accessed with an instance reference, quantify it with a type name”, and “Cannot implicity convert type void to GameLogic.CombatEvent”- is this a silly mistake I’ve made with syntax, or is it impossible to subscribe to external classes this way?

‘HitEnemy’ is static, meaning the only way to access it in C# is via GameLogic.HitEnemy and not gameLogicInstance.HitEnemy, it lives in the type itself, not the instance.

You delegate GameEvent returns void and takes no parameters, yet you’re trying to add handlers that return void an take an integer, make up your mind :smiley: - Modify your delegate to take an int. i.e. public delegate void ComatEvent(int damage);

Hint: There’s a built-in delegate that matches yours in System called Action, just in case you didn’t know. So you could public static event Action HitEnemy;

Your setup is a bit weird, so you have an event in GameLogic that enemies subscribe to using their GotHit, ok… but then if you fire the event all enemies would take damage. Unless there’s something about your design I don’t understand.

I might assume you meant the opposite: there’s certain logic/operations you need to do in your game logic when the player/enemy is hit. So you do it the other way around. You let the enemies have an OnHit event, that the game logic subscribes to, when they take damage they fire the event and the logic would get notified.