Skip to content

Instantly share code, notes, and snippets.

@adamgit
Created February 28, 2022 11:07
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 adamgit/b47c074d1094fc2abd2d642c20ba29af to your computer and use it in GitHub Desktop.
Save adamgit/b47c074d1094fc2abd2d642c20ba29af to your computer and use it in GitHub Desktop.
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();
}
}
public static class GizmoRendererSimpleExample
{
[GizmoRenderer(typeof(MyMonoBehaviour))]
public static void OnDrawGizmos( MonoBehaviour source )
{
Gizmos.color = Color.magenta;
Gizmos.DrawCube(source.transform.position, Vector3.one);
}
}
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