コガネブログ

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

【Unity】EditorGUILayout.ObjectFieldの型指定の重複を無くすラッパー関数

概要

mTexture  = EditorGUILayout.ObjectField(label, mTexture,  typeof(Texture),  false) as Texture;
mMaterial = EditorGUILayout.ObjectField(label, mMaterial, typeof(Material), false) as Material;

Unityのエディタ拡張でEditorGUILayout.ObjectFieldを使用して
テクスチャやマテリアルをエディタ上で指定できるようにするときに
typeof演算子とas演算子で型の指定が重複するのが綺麗ではないので

public static partial class EditorGUILayoutCommon
{
    public static T ObjectField<T>(string label, T obj, bool allowSceneObjects) where T : UnityEngine.Object
    {
        return EditorGUILayout.ObjectField(label, obj, typeof(T), allowSceneObjects) as T;
    }
}

このような汎用関数を使っています

mTexture  = EditorGUILayoutCommon.ObjectField<Texture> (label, mTexture,  false);
mMaterial = EditorGUILayoutCommon.ObjectField<Material>(label, mMaterial, false);

型の指定の重複が無くなるのでわかりやすく書けます

関連記事