Created
August 10, 2023 18:53
-
-
Save hk0i/98ead33ed1d4b282cacb2ca1e2d1e692 to your computer and use it in GitHub Desktop.
inventory class example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
namespace Shaninja.Scripts { | |
public interface IInventory | |
{ | |
void AddCoin(); | |
void SetTotalCoins(int total); | |
void Reset(); | |
void RegisterCoinListener(CoinListener coinListener); | |
interface CoinListener | |
{ | |
void OnCoinsUpdated(int possessed, int total); | |
} | |
} | |
public class Inventory: IInventory | |
{ | |
int _coins; | |
int _totalCoins; | |
static Inventory _instance; | |
readonly List<IInventory.CoinListener> _coinListeners = new(); | |
public static Inventory Instance | |
{ | |
get | |
{ | |
return _instance ??= new Inventory(); | |
} | |
} | |
public void AddCoin() | |
{ | |
SetCoins(++_coins); | |
} | |
public void SetCoins(int coins) | |
{ | |
if (coins < 0) return; | |
_coins = coins; | |
EmitCoinUpdate(); | |
} | |
public void SetTotalCoins(int total) | |
{ | |
_totalCoins = total; | |
EmitCoinUpdate(); | |
} | |
public void Reset() | |
{ | |
_coins = 0; | |
_totalCoins = 0; | |
} | |
public void RegisterCoinListener(IInventory.CoinListener coinListener) | |
{ | |
_coinListeners.Add(coinListener); | |
EmitCoinUpdate(); | |
} | |
void EmitCoinUpdate() | |
{ | |
Debug.Log($"Listeners: {_coinListeners.Count}; {_coins}/{_totalCoins}"); | |
_coinListeners.ForEach(listener => listener.OnCoinsUpdated(_coins, _totalCoins)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment