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.

98 lines
3.1KB

  1. #region
  2. using System.Collections.Generic;
  3. using Svelto.Context.Legacy;
  4. using Svelto.DataStructures;
  5. using UnityEngine;
  6. #endregion
  7. namespace Svelto.Context.Legacy
  8. {
  9. public class GameObjectFactory : Factories.IGameObjectFactory
  10. {
  11. public GameObjectFactory(IUnityContextHierarchyChangedListener root)
  12. {
  13. _unityContext = new WeakReference<IUnityContextHierarchyChangedListener>(root);
  14. _prefabs = new Dictionary<string, GameObject[]>();
  15. }
  16. public GameObject Build(string prefabName)
  17. {
  18. DesignByContract.Check.Require(_prefabs.ContainsKey(prefabName), "Svelto.Factories.IGameObjectFactory - Invalid Prefab Type");
  19. var go = Build(_prefabs[prefabName][0]);
  20. GameObject parent = _prefabs[prefabName][1];
  21. if (parent != null)
  22. {
  23. Transform transform = go.transform;
  24. var scale = transform.localScale;
  25. var rotation = transform.localRotation;
  26. var position = transform.localPosition;
  27. parent.SetActive(true);
  28. transform.parent = parent.transform;
  29. transform.localPosition = position;
  30. transform.localRotation = rotation;
  31. transform.localScale = scale;
  32. }
  33. return go;
  34. }
  35. /// <summary>
  36. /// Register a prefab to be built later using a string ID.
  37. /// </summary>
  38. /// <param name="prefab">original prefab</param>
  39. public GameObject Build(GameObject prefab)
  40. {
  41. DesignByContract.Check.Require(_unityContext.IsAlive == true, "Context is used, but not alive");
  42. UnityEngine.Profiling.Profiler.BeginSample("GameObject Factory Build");
  43. var copy = Object.Instantiate(prefab) as GameObject;
  44. var components = copy.GetComponentsInChildren<MonoBehaviour>(true);
  45. for (var i = 0; i < components.Length; ++i)
  46. {
  47. var monoBehaviour = components[i];
  48. if (monoBehaviour != null)
  49. {
  50. var currentGo = monoBehaviour.gameObject;
  51. _unityContext.Target.OnMonobehaviourAdded(monoBehaviour);
  52. if (currentGo.GetComponent<NotifyComponentsRemoved>() == null)
  53. currentGo.AddComponent<NotifyComponentsRemoved>().unityContext = _unityContext;
  54. }
  55. else
  56. {
  57. //Utility.Console.Log("delete me");
  58. }
  59. }
  60. UnityEngine.Profiling.Profiler.EndSample();
  61. return copy;
  62. }
  63. public void RegisterPrefab(GameObject prefab, string prefabName, GameObject parent = null)
  64. {
  65. var objects = new GameObject[2];
  66. objects[0] = prefab; objects[1] = parent;
  67. _prefabs.Add(prefabName, objects);
  68. }
  69. Dictionary<string, GameObject[]> _prefabs;
  70. WeakReference<IUnityContextHierarchyChangedListener> _unityContext;
  71. }
  72. }