Skip to content

Instantly share code, notes, and snippets.

@hk0i
Created August 10, 2023 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hk0i/98ead33ed1d4b282cacb2ca1e2d1e692 to your computer and use it in GitHub Desktop.
Save hk0i/98ead33ed1d4b282cacb2ca1e2d1e692 to your computer and use it in GitHub Desktop.
inventory class example
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