Skip to content
Snippets Groups Projects
Commit f328c63c authored by Robin Halseth Sandvik's avatar Robin Halseth Sandvik
Browse files

Added AbilityService.

- Handles Abilities and controlling them.
parent 92bc6971
No related branches found
No related tags found
1 merge request!25Ability rework.
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
fileFormatVersion: 2
guid: accabe59812fa39448d6bd558041692d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment