Hierarchy.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. namespace SRF
  2. {
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using UnityEngine;
  7. public class Hierarchy
  8. {
  9. private static readonly char[] Seperator = {'/'};
  10. private static readonly Dictionary<string, Transform> Cache = new Dictionary<string, Transform>();
  11. [Obsolete("Use static Get() instead")]
  12. public Transform this[string key]
  13. {
  14. get { return Get(key); }
  15. }
  16. /// <summary>
  17. /// Pass in a path (e.g. /Test/Me/One) and get a transform with the hierarchy Test->Me->One.
  18. /// Any Transforms required below this path will be auto-created.
  19. /// This is a very slow method, so use only on initialisation.
  20. /// </summary>
  21. /// <param name="key"></param>
  22. /// <returns></returns>
  23. public static Transform Get(string key)
  24. {
  25. Transform t;
  26. // Check cache
  27. if (Cache.TryGetValue(key, out t))
  28. {
  29. return t;
  30. }
  31. var find = GameObject.Find(key);
  32. if (find)
  33. {
  34. t = find.transform;
  35. Cache.Add(key, t);
  36. return t;
  37. }
  38. // Find container parent
  39. var elements = key.Split(Seperator, StringSplitOptions.RemoveEmptyEntries);
  40. // Create new container
  41. t = new GameObject(elements.Last()).transform;
  42. Cache.Add(key, t);
  43. // If root
  44. if (elements.Length == 1)
  45. {
  46. return t;
  47. }
  48. t.parent = Get(string.Join("/", elements, 0, elements.Length - 1));
  49. return t;
  50. }
  51. #if (!UNITY_2017 && !UNITY_2018 && !UNITY_2019) || UNITY_2019_3_OR_NEWER
  52. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
  53. public static void RuntimeInitialize()
  54. {
  55. // To handle entering play mode without a domain reload, need to reset the state of the service manager.
  56. Cache.Clear();
  57. }
  58. #endif
  59. }
  60. }