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.

85 lines
2.4KB

  1. #region
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. #endregion
  5. namespace Svelto.Context
  6. {
  7. public class GameObjectFactory: Factories.IGameObjectFactory
  8. {
  9. public GameObjectFactory(IUnityContextHierarchyChangedListener root)
  10. {
  11. _unityContext = root;
  12. _prefabs = new Dictionary<string, GameObject[]>();
  13. }
  14. /// <summary>
  15. /// Register a prefab to be built later using a string ID.
  16. /// </summary>
  17. /// <param name="prefab">original prefab</param>
  18. /// <param name="prefabName">prefab name</param>
  19. /// <param name="parent">optional gameobject to specify as parent later</param>
  20. public void RegisterPrefab(GameObject prefab, string prefabName, GameObject parent = null)
  21. {
  22. var objects = new GameObject[2];
  23. objects[0] = prefab; objects[1] = parent;
  24. _prefabs.Add(prefabName, objects);
  25. }
  26. public GameObject Build(string prefabName)
  27. {
  28. DesignByContract.Check.Require(_prefabs.ContainsKey(prefabName), "Svelto.Factories.IGameObjectFactory - Invalid Prefab Type");
  29. var go = Build(_prefabs[prefabName][0]);
  30. GameObject parent = _prefabs[prefabName][1];
  31. if (parent != null)
  32. {
  33. Transform transform = go.transform;
  34. var scale = transform.localScale;
  35. var rotation = transform.localRotation;
  36. var position = transform.localPosition;
  37. parent.SetActive(true);
  38. transform.parent = parent.transform;
  39. transform.localPosition = position;
  40. transform.localRotation = rotation;
  41. transform.localScale = scale;
  42. }
  43. return go;
  44. }
  45. public GameObject Build(GameObject go)
  46. {
  47. var copy = Object.Instantiate(go) as GameObject;
  48. var components = copy.GetComponentsInChildren<MonoBehaviour>(true);
  49. for (var i = 0; i < components.Length; ++i)
  50. if (components[i] != null)
  51. _unityContext.OnMonobehaviourAdded(components[i]);
  52. _unityContext.OnGameObjectAdded(copy);
  53. copy.AddComponent<NotifyComponentsRemoved>().unityContext = _unityContext;
  54. copy.AddComponent<NotifyEntityRemoved>().unityContext = _unityContext;
  55. return copy;
  56. }
  57. IUnityContextHierarchyChangedListener _unityContext;
  58. Dictionary<string, GameObject[]> _prefabs;
  59. }
  60. }