うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】Reflection を利用して Unity の internal 処理を利用する

internal と書いてあるけど private でも問題無くできます

static ではない場合はインスタンスを取得する必要がある のでインスタンス取得処理も記述してあります ※全部ProjectBrowserですが・・・

Type の取得

// ProjectBrowser の Typeを取得
var type = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(t => t.Name == "ProjectBrowser")
    .Select(t => t).First();
 
// どのクラス内にあるか分かればこちらでも取得ができる
// 検索量が少ないので早い
var type = typeof(EditorWindow).Assembly.GetType("UnityEditor.ProjectBrowser");

Field の取得

// internal static EditorApplication.CallbackFunction assetLabelsChanged;
var fieldInfo = typeof(EditorApplication).GetField("assetLabelsChanged", BindingFlags.NonPublic | BindingFlags.Static);
var function = (EditorApplication.CallbackFunction) fieldInfo.GetValue(null);
function += () => { Debug.Log("changeLabel"); };
fieldInfo.SetValue(null, function);
 
// internal GUIContent m_Notification = (GUIContent) null;
var type = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(t => t.Name == "ProjectBrowser")
    .Select(t => t).First();
         
var projectBrowser = Resources.FindObjectsOfTypeAll(type)[0];
// internal GUIContent m_TitleContent;
var fieldInfo = type.GetField("m_TitleContent", BindingFlags.NonPublic | BindingFlags.Instance);
var content = (GUIContent) fieldInfo.GetValue(projectBrowser);

Property の取得

// internal static Material GUITextureBlit2SRGBMaterial
var material = typeof(EditorGUIUtility)
    .GetProperty("GUITextureBlit2SRGBMaterial", BindingFlags.Static | BindingFlags.NonPublic)
    .GetValue(typeof(EditorGUIUtility), 
    null
) as Material;
 
var type = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(t => t.Name == "ProjectBrowser")
    .Select(t => t).First();
 
var projectBrowser = Resources.FindObjectsOfTypeAll(type)[0];
// private static float k_ToolbarHeight
var propertyInfo = type.GetProperty("k_ToolbarHeight", BindingFlags.NonPublic | BindingFlags.Static);
var height = (float) propertyInfo.GetValue(projectBrowser);

Method の実行

// internal static extern string GetLicenseType();
var licenseType = typeof(EditorApplication).InvokeMember(
    "GetLicenseType",
    BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, 
    null, 
    null, 
    new object[0]
) as string;
 
var type = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(t => t.Name == "ProjectBrowser")
    .Select(t => t).First();
 
var projectBrowser = Resources.FindObjectsOfTypeAll(type)[0];
// internal string GetActiveFolderPath()
var methodInfo = type.GetMethod("GetActiveFolderPath", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);
var path = methodInfo.Invoke(projectBrowser, new object[0]) as string;