I’ve recently been working on some of the collectables logic in this 2.5D platformer I’ve been working on recently. This currently consists of a Coin script and object which will destroy itself and call a CoinsCollected event OnTriggerEnter (with the Player). As such, the Coin script itself is currently fairly barebones at the moment:
Over in my GameEvents class, I’ve got this custom event type (an ‘IntEvent’) and an instance of this with the ‘coinsCollected’ event. Whenever the public CoinsCollected method is called (and a number passed in as an argument), the coinsCollected event is invoked assuming it has any listeners.
Currently, the listeners consist of the Player class and my UIManager class. In both cases, I’m subscribing local methods to this event using the AddListener method. The local method then updates a _playerCoins variable in both cases and displays this in the case of the UIManager.
I’m fairly happy with the lack of direct references to other scripts, particularly the Player class, but I’m less keen on having both the UIManager and the Player class store their own ‘playerCoins’ integer variables. I’m thinking of shifting this over to some sort of centralised variable container; possibly using a ScriptableObject (see the ‘Architect for Variables’ section of this article). I’ve yet to do this just yet, but for now I’m fairly happy with the current coin collection system 😉