diff --git a/MrBigsock/Assets/Code/Services/AbilityService.cs b/MrBigsock/Assets/Code/Services/AbilityService.cs new file mode 100644 index 0000000000000000000000000000000000000000..1849ecf96f6096928a9ca3abc4d406f12def88f7 --- /dev/null +++ b/MrBigsock/Assets/Code/Services/AbilityService.cs @@ -0,0 +1,85 @@ +using System.Collections; +using System; +using System.Linq; +using System.Collections.Generic; +using System.Reflection; + +using UnityEngine; +using UnityEngine.InputSystem; + +using BigSock.Item; + + +namespace BigSock.Service { + + /* + Service for handling abilities. + */ + public partial class AbilityService { + /* + The instance to use. + */ + public static readonly AbilityService SINGLETON = new AbilityService(); + + /* + Get an instance of the ability of the given id. + */ + public IAbility Get(ulong id) { + if(_abilities.TryGetValue(id, out var res)) return _new(res); + return null; + } + + /* + Get a random ability from the ability pool. + */ + public IAbility GetRandom() { + var num = _rnd.Next(_abilityList.Count); + return _new(_abilityList[num]); + } + } + + public partial class AbilityService { + private Dictionary<ulong, IAbility> _abilities = new Dictionary<ulong, IAbility>(); + private List<IAbility> _abilityList = new List<IAbility>(); + + private System.Random _rnd = new System.Random(); + + private AbilityService() { + _loadItems(); + } + + /* + Load the abilities into the dictionary. + Reflection code: https://stackoverflow.com/a/6944605 + */ + private void _loadItems() { + // Get the classs that inherit the item base class. + var types = Assembly + .GetAssembly(typeof(BaseAbility)) + .GetTypes() + .Where(myType => myType.IsClass + && !myType.IsAbstract + && myType.IsSubclassOf(typeof(BaseAbility))); + + // Create list of instances. + _abilityList = types + .Select(t => (IAbility) Activator.CreateInstance(t, new object[0])) + .ToList(); + + // Map to a dictionary by their ids. + _abilities = _abilityList + .ToDictionary(t => t.Id); + + foreach(var a in _abilityList) { + Debug.Log($"[AbilityService._loadItems()] {a.Id}"); + } + } + + /* + Creates a new instance of the object. + */ + private IAbility _new(IAbility obj) + => (IAbility) Activator.CreateInstance(obj.GetType(), new object[0]); + + } +} \ No newline at end of file diff --git a/MrBigsock/Assets/Code/Services/AbilityService.cs.meta b/MrBigsock/Assets/Code/Services/AbilityService.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..ba54c4ef9e433c501d67907a37c029f02b20f6f8 --- /dev/null +++ b/MrBigsock/Assets/Code/Services/AbilityService.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: accabe59812fa39448d6bd558041692d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: