Created
February 28, 2022 11:07
-
-
Save adamgit/b47c074d1094fc2abd2d642c20ba29af 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; | |
using UnityEngine; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
using UnityEditor; | |
public class GizmoRendererAttribute : System.Attribute | |
{ | |
private Type classWithGizmos; | |
public GizmoRendererAttribute(Type t) | |
{ | |
classWithGizmos = t; | |
if( ! classWithGizmos.IsSubclassOf(typeof(MonoBehaviour))) | |
throw new Exception( "This attribute must specify a target MonoBehaviour that it will render gizmos for"); | |
} | |
public bool isRendererForClass(MonoBehaviour mb) | |
{ | |
return mb.GetType().IsAssignableFrom(classWithGizmos); | |
} | |
public static Dictionary<GizmoRendererAttribute,MethodInfo> gizmoCache; | |
public static List<MethodInfo> RenderersForObject( MonoBehaviour mb ) | |
{ | |
if(gizmoCache == null) | |
{ | |
gizmoCache = new Dictionary<GizmoRendererAttribute, MethodInfo>(); | |
var assembly = AppDomain.CurrentDomain.GetAssemblies(); | |
var gizmoRendererMethods = assembly.SelectMany( x => x.GetTypes() ) | |
.SelectMany(type => type.GetMethods()) | |
.Where(type => Attribute.IsDefined(type, typeof(GizmoRendererAttribute)) ); | |
foreach( var method in gizmoRendererMethods ) | |
if(Attribute.GetCustomAttribute(method, typeof(GizmoRendererAttribute)) is GizmoRendererAttribute attribute) | |
gizmoCache[attribute] = method; | |
} | |
return gizmoCache.Where(pair => pair.Key.isRendererForClass(mb)).Select(pair => pair.Value).ToList(); | |
} | |
} |
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
public static class GizmoRendererSimpleExample | |
{ | |
[GizmoRenderer(typeof(MyMonoBehaviour))] | |
public static void OnDrawGizmos( MonoBehaviour source ) | |
{ | |
Gizmos.color = Color.magenta; | |
Gizmos.DrawCube(source.transform.position, Vector3.one); | |
} | |
} |
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
public class MyMonoBehaviour : MonoBehaviour | |
{ | |
void OnDrawGizmos() | |
{ | |
GizmoRendererAttribute.RenderersForObject(this).ForEach(info => info.Invoke(null,new []{this})); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment