万年素人からHackerへの道

万年素人がHackerになれるまで殴り書きするぜ。

UnityのScreeは役立たずなので C#

Screen.width;
Screen.height;

などは、EditorではなぜかGame Sceneの解像度の設定から取得できない。

URL: http://kirillmuzykov.com/unity-get-game-view-resolution/

ここに解決策が!
しかもリフレクションを使っている。

public class Singleton<T> where T : class, new()
{
    static readonly T instance = new T();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton() {  }

    protected Singleton() { }

    public static T Instance { get { return instance; } }
}

とかを使って、

using UnityEngine;
using System.Collections;

public class Resolution : Singleton<Resolution>
{
#if UNITY_EDITOR
    public int ScreenHeight { get; private set; }

    public int ScreenWidth { get; private set; }

    public void SetScreenWidthAndHeightFromEditorGameViewViaReflection ()
    {
        //Taking game view using the method shown below 
        var gameView = GetMainGameView ();
        var prop = gameView.GetType ().GetProperty ("currentGameViewSize", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        var gvsize = prop.GetValue (gameView, new object[0]{});
        var gvSizeType = gvsize.GetType ();

        //I have 2 instance variable which this function sets:
        this.ScreenHeight = (int)gvSizeType.GetProperty ("height", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).GetValue (gvsize, new object[0]{});
        this.ScreenWidth = (int)gvSizeType.GetProperty ("width", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance).GetValue (gvsize, new object[0]{});
    }

    private UnityEditor.EditorWindow GetMainGameView ()
    {
        System.Type T = System.Type.GetType ("UnityEditor.GameView,UnityEditor");
        System.Reflection.MethodInfo GetMainGameView = T.GetMethod ("GetMainGameView", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
        System.Object Res = GetMainGameView.Invoke (null, null);
        return (UnityEditor.EditorWindow)Res;
    }
#endif 
}

を記載しよう。

そうすると、

        Resolution.Instance.SetScreenWidthAndHeightFromEditorGameViewViaReflection ();
        Debug.Log(Resolution.Instance.ScreenHeight);
        Debug.Log(Resolution.Instance.ScreenWidth);

のようにすれば取得できる。
Editor専用。