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.

70 lines
1.9KB

  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()
  10. {
  11. _prefabs = new Dictionary<string, GameObject[]>();
  12. }
  13. public GameObject Build(string prefabName)
  14. {
  15. DesignByContract.Check.Require(_prefabs.ContainsKey(prefabName), "Svelto.Factories.IGameObjectFactory -prefab was not found:" + prefabName);
  16. var go = Build(_prefabs[prefabName][0]);
  17. GameObject parent = _prefabs[prefabName][1];
  18. if (parent != null)
  19. {
  20. Transform transform = go.transform;
  21. var scale = transform.localScale;
  22. var rotation = transform.localRotation;
  23. var position = transform.localPosition;
  24. parent.SetActive(true);
  25. transform.parent = parent.transform;
  26. transform.localPosition = position;
  27. transform.localRotation = rotation;
  28. transform.localScale = scale;
  29. }
  30. return go;
  31. }
  32. /// <summary>
  33. /// Register a prefab to be built later using a string ID.
  34. /// </summary>
  35. /// <param name="prefab">original prefab</param>
  36. public GameObject Build(GameObject prefab)
  37. {
  38. UnityEngine.Profiling.Profiler.BeginSample("GameObject Factory Build");
  39. var copy = Object.Instantiate(prefab) as GameObject;
  40. return copy;
  41. }
  42. public void RegisterPrefab(GameObject prefab, string prefabName, GameObject parent = null)
  43. {
  44. var objects = new GameObject[2];
  45. objects[0] = prefab; objects[1] = parent;
  46. _prefabs.Add(prefabName, objects);
  47. }
  48. Dictionary<string, GameObject[]> _prefabs;
  49. }
  50. }