【Unity】【シェーダ】シェーダプロパティ用のアトリビュートを自作するMaterialPropertyDrawer

シェーダプロパティ用のアトリビュートを自作するMaterialPropertyDrawerの使い方です。

Unity2018.3.1

MaterialPropertyDrawerを継承したクラスを作る

まずはMaterialPropertyDrawerを継承したクラスを作ります。
クラス名はXxxDrawerという命名にします。
(ファイル名とクラス名を合わせたりする必要はとくにはありません。)

using UnityEngine;
using UnityEditor;

// MaterialPropertyDrawerを継承したクラスを「XxxDrawerという名前で」作る
public class ClampDrawer : MaterialPropertyDrawer
{
    private float _min;
    private float _max;

    public ClampDrawer(float min, float max){
        _min = min;
        _max = max;
    }

    public override void OnGUI(Rect position, MaterialProperty prop, GUIContent label, MaterialEditor editor)
    {
        // 描画
        var value = EditorGUI.FloatField(position, prop.displayName, prop.floatValue);
        
        // Clamp
        value = Mathf.Clamp(value, _min, _max);

        // プロパティ更新
        prop.floatValue = value;
    }
}

説明はコメントの通りです。
書き方は普通の(シェーダプロパティじゃない方の)PropertyDrawerとそんなに変わりません。

ちなみに普通のPropertyDrawerの書き方はこちら。

light11.hatenadiary.com

シェーダで使う

後はシェーダで使うだけです。

Shader "Unlit/NewUnlitShader"
{
    Properties
    {
        // ClampDrawerからDrawerを削除したClampがアトリビュート名
        [Clamp(0.0, 1.0)]
        _Example ("Example", float) = 0
    }
    SubShader
    {      
        Pass
        {
            CGPROGRAM

           #pragma vertex vert
           #pragma fragment frag
           #include "UnityCG.cginc"

            float4 vert (float4 vertex : POSITION) : SV_POSITION
            {
                return UnityObjectToClipPos(vertex);
            }

            fixed4 frag () : SV_Target
            {
                return 1;
            }

            ENDCG
        }
    }
}

結果

f:id:halya_11:20190119232501p:plain

これで0~1に丸められるfloatのプロパティが描画されました。

関連

実際に活用している記事

light11.hatenadiary.com

シェーダプロパティじゃない方のPropertyDrawerの記事

light11.hatenadiary.com

参考

docs.unity3d.com