LoginSignup
15
16

More than 5 years have passed since last update.

Unity5のGUIクラスに追加されたScopeについて

Posted at

Begin/Endで行うGUIグループのヘルパー機能。usingステートを使ってIDisposableオブジェクトとして表現することが出来るようになりました。

使い方

今までは

void OnGUI ()
{
    GUILayout.BeginHorizontal();

    GUILayout.Label("Label 1");
    GUILayout.Label("Label 2");

    GUILayout.EndHorizontal();
}

これからは以下のようにして管理することが出来るようです。

void OnGUI ()
{
    using (var scope = new GUILayout.HorizontalScope()) {

        GUILayout.Label ("Label 1");
        GUILayout.Label ("Label 2");

    }
}

オリジナルのScopeを作成する

HorizontalScopeをアセンブリブラウザで見てみるとGUI.Scopeを継承して作成することが出来るみたいですね。

ss 2015-03-08 14.30.20.png

IndentScopeを作成してみる

エディターGUIではEditorGUI.indentLevelによってインデントを変更することが可能です。これをScopeで実装してみましょう。

IndentScope.cs
using UnityEngine;
using UnityEditor;
public class IndentScope : GUI.Scope
{
    int _indentLevel;

    public IndentScope (int indentLevel)
    {
        _indentLevel = EditorGUI.indentLevel;
        EditorGUI.indentLevel = indentLevel;
    }

    protected override void CloseScope ()
    {
        EditorGUI.indentLevel = _indentLevel;
    }
}

以下のように使用することが出来ます。

NewBehaviourScript.cs
using UnityEngine;
using System.Collections;
using UnityEditor;

public class NewBehaviourScript : EditorWindow
{
    [MenuItem("Window/Example")]
    static void Open ()
    {
        GetWindow<NewBehaviourScript> ();
    }

    void OnGUI ()
    {
        using (var scope = new IndentScope(0)) {
            EditorGUILayout.LabelField ("IndentLevel 0");
        }

        using (var scope = new IndentScope(1)) {
            EditorGUILayout.LabelField ("IndentLevel 1");
        }

        using (var scope = new IndentScope(2)) {
            EditorGUILayout.LabelField ("IndentLevel 2");
        }
    }
}

ss 2015-03-08 15.16.49.png

15
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
16