KeyManager.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Linq;
  5. using UnityEngine;
  6. using Random = UnityEngine.Random;
  7. namespace DunGen
  8. {
  9. [Serializable]
  10. [CreateAssetMenu(menuName = "DunGen/Key Manager", order = 700)]
  11. public sealed class KeyManager : ScriptableObject
  12. {
  13. public ReadOnlyCollection<Key> Keys
  14. {
  15. get
  16. {
  17. if (keysReadOnly == null)
  18. keysReadOnly = new ReadOnlyCollection<Key>(keys);
  19. return keysReadOnly;
  20. }
  21. }
  22. private ReadOnlyCollection<Key> keysReadOnly;
  23. [SerializeField]
  24. private List<Key> keys = new List<Key>();
  25. public Key CreateKey()
  26. {
  27. Key key = new Key(GetNextAvailableID());
  28. key.Name = UnityUtil.GetUniqueName("New Key", keys.Select(x => x.Name));
  29. key.Colour = new Color(Random.value, Random.value, Random.value);
  30. keys.Add(key);
  31. return key;
  32. }
  33. public void DeleteKey(int index)
  34. {
  35. keys.RemoveAt(index);
  36. }
  37. public Key GetKeyByID(int id)
  38. {
  39. return keys.Where(x => { return x.ID == id; }).FirstOrDefault();
  40. }
  41. public Key GetKeyByName(string name)
  42. {
  43. return keys.Where(x => { return x.Name == name; }).FirstOrDefault();
  44. }
  45. public bool RenameKey(int index, string newName)
  46. {
  47. if(keys[index].Name == newName)
  48. return false;
  49. newName = UnityUtil.GetUniqueName(newName, keys.Select(x => x.Name));
  50. keys[index].Name = newName;
  51. return true;
  52. }
  53. private int GetNextAvailableID()
  54. {
  55. int nextID = 0;
  56. foreach(var key in keys.OrderBy(x => x.ID))
  57. {
  58. if(key.ID >= nextID)
  59. nextID = key.ID + 1;
  60. }
  61. return nextID;
  62. }
  63. }
  64. }