Created
July 19, 2019 03:43
-
-
Save neogeek/9afb128659f854d03369ce1a25aaefef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using UnityEditor; | |
using UnityEngine; | |
public static class Unity2DComponents | |
{ | |
[MenuItem("GameObject/2D Object/Box", false, 0)] | |
private static void Create2DCube() | |
{ | |
var gameObject = GameObject.CreatePrimitive(PrimitiveType.Cube); | |
if (Selection.activeGameObject) | |
{ | |
gameObject.transform.parent = Selection.activeGameObject.transform; | |
} | |
gameObject.name = GenerateNameForGameObjectWithComponent<BoxCollider2D>(gameObject, "Box"); | |
Object.DestroyImmediate(gameObject.GetComponent<BoxCollider>()); | |
gameObject.AddComponent<BoxCollider2D>(); | |
Selection.activeGameObject = gameObject; | |
} | |
[MenuItem("GameObject/2D Object/Circle", false, 0)] | |
private static void Create2Sphere() | |
{ | |
var gameObject = GameObject.CreatePrimitive(PrimitiveType.Sphere); | |
if (Selection.activeGameObject) | |
{ | |
gameObject.transform.parent = Selection.activeGameObject.transform; | |
} | |
gameObject.name = GenerateNameForGameObjectWithComponent<CircleCollider2D>(gameObject, "Circle"); | |
Object.DestroyImmediate(gameObject.GetComponent<SphereCollider>()); | |
gameObject.AddComponent<CircleCollider2D>(); | |
Selection.activeGameObject = gameObject; | |
} | |
private static string GenerateNameForGameObjectWithComponent<T>(GameObject gameObject, string name) where T : Component | |
{ | |
T[] others; | |
if (gameObject.transform.parent) | |
{ | |
others = gameObject.transform.parent.GetComponentsInChildren<T>() | |
.Where(t => t.transform.parent.Equals(gameObject.transform.parent)).ToArray(); | |
} | |
else | |
{ | |
others = Object.FindObjectsOfType<T>() | |
.Where(t => t.transform.parent == null).ToArray(); | |
} | |
var updatedName = name; | |
if (others.Length > 0) | |
{ | |
updatedName = string.Format("{0} ({1})", updatedName, others.Length); | |
} | |
return updatedName; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment