diff --git a/MrBigsock/Assets/Code/Services/ItemService.cs b/MrBigsock/Assets/Code/Services/ItemService.cs index 0317388eb055b956de63c35b3f620820939496b8..c739901a0b11b6f58a92ea998f302303a2fdb83c 100644 --- a/MrBigsock/Assets/Code/Services/ItemService.cs +++ b/MrBigsock/Assets/Code/Services/ItemService.cs @@ -2,6 +2,8 @@ using System.Collections; using System; using System.Linq; using System.Collections.Generic; +using System.Reflection; + using UnityEngine; using UnityEngine.InputSystem; @@ -13,20 +15,36 @@ namespace BigSock.Service { /* Service for handling items. */ - public class ItemService { + public partial class ItemService { /* The instance to use. */ public static readonly ItemService SINGLETON = new ItemService(); + /* + Get an instance of the item of the given id. + */ + public IItem Get(ulong id) { + if(_items.TryGetValue(id, out var res)) return _new(res); + return null; + } + /* + Get a random item from the item pool. + */ + public IItem GetRandom() { + var num = _rnd.Next(_itemList.Count); + return _new(_itemList[num]); + } + + } + + public partial class ItemService { private Dictionary<ulong, IItem> _items = new Dictionary<ulong, IItem>(); private List<IItem> _itemList = new List<IItem>(); - private System.Random _rnd = new System.Random(); - private ItemService() { _loadItems(); } @@ -34,39 +52,32 @@ namespace BigSock.Service { /* Load the items into the dictionary. (Hard-coded for now, use reflection later) + Reflection code: https://stackoverflow.com/a/6944605 */ private void _loadItems() { - _items = new Dictionary<ulong, IItem>{ - { 101, new ItemRunningShoes() }, - { 201, new ItemFourEyes() }, - { 102, new ItemLunch() }, - { 103, new ItemCoffee() }, - }; - - _itemList = _items.Values.ToList(); - } + // Get the classs that inherit the item base class. + var types = Assembly + .GetAssembly(typeof(ItemBase)) + .GetTypes() + .Where(myType => myType.IsClass + && !myType.IsAbstract + && myType.IsSubclassOf(typeof(ItemBase))); - /* - Creates a new instance of the object. - */ - //private T _new<T>(T obj) where T : IItem, new() { return new T(); } - private T _new<T>(T obj) where T : IItem { return obj; } + // Create list of instances. + _itemList = types + .Select(t => (IItem) Activator.CreateInstance(t, new object[0])) + .ToList(); - /* - Get an instance of the item of the given id. - */ - public IItem Get(ulong id) { - if(_items.TryGetValue(id, out var res)) return _new(res); - return null; + // Map to a dictionary by their ids. + _items = _itemList + .ToDictionary(t => t.Id); } /* - Get a random item from the item pool. + Creates a new instance of the object. */ - public IItem GetRandom() { - var num = _rnd.Next(_itemList.Count); - return _new(_itemList[num]); - } - + private IItem _new(IItem obj) + => (IItem) Activator.CreateInstance(obj.GetType(), new object[0]); + } } \ No newline at end of file