Notifications are good for this kind of problem. There is no direct connection between objects at all, and it is very expandable if more than one object needs to be known (for example, your health component, a higher-level game object that determines the game, even an opponent / ally's AI can behave differently when health is low).
You may have a notification called playerHealthChanged, and your health bar component and other objects will be registered independently to respond to this event. (You probably need to tell the HealthComponent instance whether it should publish this notification, so only the player should publish - maybe it can use isKind (of :) on its essence, or just have a bool field to enable the publication, which is set to true for player instance).
I usually put all the definitions of notification names in one module so that any class can access them:
let kPlayerHealthChangedNotification = Notification.Name("playerHealthChanged")
Here's the way the component will post a notification (you can optionally pass an object other than self):
NotificationCenter.default.post(name: kPlayerHealthChangedNotification, object:self)
Then objects that take care of changes in the player’s health can be registered in the same way as in the initialization code - create a handler function, and then add yourself as an observer for notification:
@objc func onPlayerHealthChanged(_ notification:Notification) { // do whatever is needed; notification.object // has the object from the post } // put this in a setup method - init or similar: NotificationCenter.default.addObserver(self, selector:
Here is the documentation: https://developer.apple.com/documentation/foundation/notifications
source share