GameObjectCreation.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using UnityEditor.SceneManagement;
  3. using UnityEngine;
  4. using UnityEngine.U2D;
  5. namespace UnityEditor.U2D
  6. {
  7. static class GameObjectCreation
  8. {
  9. const int k_PixelPerfectCameraGameObjectMenuPriority = 5;
  10. [MenuItem("GameObject/2D Object/Pixel Perfect Camera", priority = k_PixelPerfectCameraGameObjectMenuPriority)]
  11. static void GameObjectCreatePixelPerfectCamera(MenuCommand menuCommand)
  12. {
  13. var go = CreateGameObject("Pixel Perfect Camera", menuCommand, new []{typeof(PixelPerfectCamera)});
  14. go.GetComponent<PixelPerfectCamera>().pixelSnapping = true;
  15. }
  16. static public GameObject CreateGameObject(string name, MenuCommand menuCommand, params Type[] components)
  17. {
  18. var parent = menuCommand.context as GameObject;
  19. var newGO = ObjectFactory.CreateGameObject(name, components);
  20. newGO.name = name;
  21. Selection.activeObject = newGO;
  22. Place(newGO, parent);
  23. if (EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D)
  24. {
  25. var position = newGO.transform.position;
  26. position.z = 0;
  27. newGO.transform.position = position;
  28. }
  29. Undo.RegisterCreatedObjectUndo(newGO, string.Format("Create {0}", name));
  30. return newGO;
  31. }
  32. internal static void Place(GameObject go, GameObject parentTransform)
  33. {
  34. if (parentTransform != null)
  35. {
  36. var transform = go.transform;
  37. Undo.SetTransformParent(transform, parentTransform.transform, "Reparenting");
  38. transform.localPosition = Vector3.zero;
  39. transform.localRotation = Quaternion.identity;
  40. transform.localScale = Vector3.one;
  41. go.layer = parentTransform.gameObject.layer;
  42. if (parentTransform.GetComponent<RectTransform>())
  43. ObjectFactory.AddComponent<RectTransform>(go);
  44. }
  45. else
  46. {
  47. PlaceGameObjectInFrontOfSceneView(go);
  48. StageUtility.PlaceGameObjectInCurrentStage(go); // may change parent
  49. }
  50. // Only at this point do we know the actual parent of the object and can modify its name accordingly.
  51. GameObjectUtility.EnsureUniqueNameForSibling(go);
  52. Undo.SetCurrentGroupName("Create " + go.name);
  53. Selection.activeGameObject = go;
  54. }
  55. internal static void PlaceGameObjectInFrontOfSceneView(GameObject go)
  56. {
  57. var view = SceneView.lastActiveSceneView;
  58. if (view != null)
  59. {
  60. view.MoveToView(go.transform);
  61. }
  62. }
  63. }
  64. }