万年素人からHackerへの道

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

  • ・資産運用おすすめ
    10万円は1000円くらい利益
    資産運用ブログ アセマネ
    • ・寄付お願いします
      YENTEN:YYzNPzdsZWqr5THWAdMrKDj7GT8ietDc2W
      BitZenny:ZfpUbVya8MWQkjjGJMjA7P9pPkqaLnwPWH
      c0ban:8KG95GXdEquNpPW8xJAJf7nn5kbimQ5wj1
      Skycoin:KMqcn7x8REwwzMHPi9fV9fbNwdofYAWKRo

    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専用。