Skip to content

Instantly share code, notes, and snippets.

@neogeek
Created July 19, 2019 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neogeek/9afb128659f854d03369ce1a25aaefef to your computer and use it in GitHub Desktop.
Save neogeek/9afb128659f854d03369ce1a25aaefef to your computer and use it in GitHub Desktop.
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