Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.4KB

  1. using UnityEngine;
  2. using Svelto.Context;
  3. using System.Collections;
  4. public class UnityContext:MonoBehaviour
  5. {}
  6. public class UnityContext<T>: UnityContext where T:class, ICompositionRoot, IUnityContextHierarchyChangedListener, new()
  7. {
  8. virtual protected void Awake()
  9. {
  10. Init();
  11. }
  12. void Init()
  13. {
  14. _applicationRoot = new T();
  15. MonoBehaviour[] behaviours = transform.GetComponentsInChildren<MonoBehaviour>(true);
  16. for (int i = 0; i < behaviours.Length; i++)
  17. {
  18. var component = behaviours[i];
  19. if (component != null)
  20. _applicationRoot.OnMonobehaviourAdded(component);
  21. }
  22. Transform[] children = transform.GetComponentsInChildren<Transform>(true);
  23. for (int i = 0; i < children.Length; i++)
  24. {
  25. var child = children[i];
  26. if (child != null)
  27. _applicationRoot.OnGameObjectAdded(child.gameObject);
  28. }
  29. }
  30. void OnDestroy()
  31. {
  32. FrameworkDestroyed();
  33. }
  34. void Start()
  35. {
  36. if (Application.isPlaying == true)
  37. StartCoroutine(WaitForFrameworkInitialization());
  38. }
  39. IEnumerator WaitForFrameworkInitialization()
  40. {
  41. yield return new WaitForEndOfFrame(); //let's wait until next frame, so we are sure that all the awake and starts are called
  42. _applicationRoot.OnContextInitialized();
  43. }
  44. void FrameworkDestroyed()
  45. {
  46. _applicationRoot.OnContextDestroyed();
  47. }
  48. private T _applicationRoot = null;
  49. }