はじめに
エディタ拡張からGameView周りを操作するメモ書き。
GameViewは操作のための標準のAPIは公開されていませんが、Reflectionという方法を用いて一部機能にアクセスすることができます。
その中の1つに解像度を選択する部分のインデックスを取得、設定するプロパティがあるのですが、これの仕様がどこかのタイミングで変わっているようなので、記事として残します。
環境
Unity:6000.0.32f1
GameViewの解像度indexの設定
GameViewの解像度indexとは下図のどれが選択されているかをインデックスで表したものです。

これをエディタ拡張から設定、取得することができます。
サンプル実装
public static class SampleClass
{
#region types
private static class Types
{
private static string assemblyName = "UnityEditor.dll";
private static Assembly assembly = Assembly.Load(assemblyName);
public static Type gameViewType = assembly.GetType("UnityEditor.GameView");
}
#endregion
/// <summary>
/// ゲームビューのサイズインデックスを直接指定して設定します
/// </summary>
/// <param name="index">設定するインデックス</param>
/// <returns>設定に成功したかどうか</returns>
public static bool SetSelectedSizeIndex(int index)
{
try
{
// GameViewのウィンドウを取得
EditorWindow gameView = EditorWindow.GetWindow(Types.gameViewType);
// 選択されているサイズインデックスのプロパティを取得
PropertyInfo selectedSizeIndex = Types.gameViewType.GetProperty("selectedSizeIndex", BindingFlags.Instance | BindingFlags.Public);
if (selectedSizeIndex != null)
{
// インデックスを設定
selectedSizeIndex.SetValue(gameView, index, null);
return true;
}
}
catch (Exception ex)
{
Debug.LogError($"Failed to set game view size index: {ex.Message}");
}
return false;
}
/// <summary>
/// 現在選択されているゲームビューのサイズインデックスを取得します
/// </summary>
/// <returns>現在選択されているインデックス。取得に失敗した場合は-1</returns>
public static int GetSelectedSizeIndex()
{
try
{
// GameViewのウィンドウを取得
EditorWindow gameView = EditorWindow.GetWindow(Types.gameViewType);
// 選択されているサイズインデックスのプロパティを取得
PropertyInfo selectedSizeIndex = Types.gameViewType.GetProperty("selectedSizeIndex", BindingFlags.Instance | BindingFlags.Public);
if (selectedSizeIndex != null)
{
// インデックスを取得
return (int)selectedSizeIndex.GetValue(gameView, null);
}
}
catch (Exception ex)
{
Debug.LogError($"Failed to get game view size index: {ex.Message}");
}
return -1;
}
}
重要なのは下記の部分で、新しいUnityではBindingFlags.Publicでアクセスできるのですが、古いUnityの場合はNonPublicでアクセスする必要があったようです。
PropertyInfo selectedSizeIndex = Types.gameViewType.GetProperty("selectedSizeIndex", BindingFlags.Instance | BindingFlags.Public);
古いAssetを使用している場合には上記によりプロパティが取得できない場合があるようなので、Public設定を変えてみるとアクセスできるようになるかもしれません。
さいごに
以上
自分がハマったポイントなので、残しておくための記事ですが、最後までお読みいただきありがとうございます。
コメント