Skip to content

Instantly share code, notes, and snippets.

@atori708
Last active December 20, 2022 12:35
Show Gist options
  • Save atori708/c7c1fdb18f45ebed3485dc7b74248327 to your computer and use it in GitHub Desktop.
Save atori708/c7c1fdb18f45ebed3485dc7b74248327 to your computer and use it in GitHub Desktop.
Gizmo表示をスクリプトから制御する(2022.1以前のリフレクションを使った手法)
/// <summary>
/// Gizmo表示をスクリプトから変更するためのクラス
/// </summary>
public class GizmoVisibleSwitcher
{
Type annotation;
Type annotationUtility;
MethodInfo getAnnotations;
MethodInfo setGizmoEnabled;
MethodInfo setIconEnabled;
public GizmoVisibleSwitcher()
{
annotation = Type.GetType("UnityEditor.Annotation, UnityEditor");
annotationUtility = Type.GetType("UnityEditor.AnnotationUtility, UnityEditor");
getAnnotations = annotationUtility.GetMethod("GetAnnotations", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
setGizmoEnabled = annotationUtility.GetMethod("SetGizmoEnabled", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
setIconEnabled = annotationUtility.GetMethod("SetIconEnabled", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
}
/// <summary>
/// すべてのGizmoの表示非表示を切り替える
/// </summary>
/// <param name="value">true:表示 false:非表示</param>
public void SwitchAllGizmos(bool value)
{
var classId = annotation.GetField("classID");
var scriptClass = annotation.GetField("scriptClass");
var visible = value ? 1 : 0;
var annotations = (Array)getAnnotations.Invoke(null, null);
foreach (var annotation in annotations) {
var classIdValue = (int)classId.GetValue(annotation);
var scriptClassValue = (string)scriptClass.GetValue(annotation);
setGizmoEnabled.Invoke(null, new object[] { classIdValue, scriptClassValue, visible, false });
setIconEnabled.Invoke(null, new object[] { classIdValue, scriptClassValue, visible});
}
}
/// <summary>
/// <typeparamref name="T"/> のGizmoの表示非表示を切り替える
/// </summary>
/// <param name="value">true:表示 false:非表示</param>
/// <typeparam name="T">切り替えたい型</typeparam>
public void SwitchGizmo<T>(bool value) where T : Component
{
var typeName = typeof(T).Name;
var classId = annotation.GetField("classID");
var scriptClass = annotation.GetField("scriptClass");
var visible = value ? 1 : 0;
var annotations = (Array)getAnnotations.Invoke(null, null);
foreach (var annotation in annotations) {
var scriptClassValue = (string)scriptClass.GetValue(annotation);
if (scriptClassValue.Equals(typeName) == false) {
continue;
}
var classIdValue = (int)classId.GetValue(annotation);
setGizmoEnabled.Invoke(null, new object[] { classIdValue, scriptClassValue, visible, false });
setIconEnabled.Invoke(null, new object[] { classIdValue, scriptClassValue, visible });
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment