コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】スクリプトから Game ビューの Scale を変更する方法

概要

using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;

internal static class Example
{
    [MenuItem( "hoge/hoge" )]
    private static void Hoge()
    {
        const BindingFlags bindingAttrs = BindingFlags.Instance | BindingFlags.NonPublic;

        var type              = Type.GetType( "UnityEditor.GameView,UnityEditor" );
        var editorWindow      = EditorWindow.GetWindow( type );
        var zoomAreaFieldInfo = type.GetField( "m_ZoomArea", bindingAttrs );
        var zoomArea          = zoomAreaFieldInfo.GetValue( editorWindow );
        var scaleFieldInfo    = zoomArea.GetType().GetField( "m_Scale", bindingAttrs );

        scaleFieldInfo.SetValue( zoomArea, Vector2.one );
    }
}