Shaderで表示するプロパティーをToggleでOn,Offする[Unity]


プロパティー

表示したいプロパティーには名前の頭に"_SubTex"とつけます.

    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
...
        // SubTexture
        [Toggle(USE_SUB_TEXTURE)] _UseSubTexture ("Use SubTexture", Float) = 0
        _SubTex("Sub Texture", 2D) = "white"{}
        [Header(Blend)]
        [KeywordEnum(Add, Mix)]
         _SubTexBlend("Blend", Float) = 0
         _SubTexBlendIntensity("Intensity", Range(0,1)) = 1
    }

Editor

using System.Collections;
using System.Collections.Generic;
using UnityEditor;

public class TSpritesEffectEditor : ShaderGUI {

    public override void OnGUI (MaterialEditor materialEditor, MaterialProperty[] properties)
    {
        var subTexToggle = ShaderGUI.FindProperty ("_UseSubTexture", properties);
        TShaderGUIUtils.DrawProperties (subTexToggle, "_SubTex", materialEditor, properties);
    }
}

ポイント

  • ShaderGUIを継承(MaterialEditorではない)
  • Toggleを取得
  • DrawPropertiesを呼ぶ

Util

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;

public static class TShaderGUIUtils {
    /// <summary>
    /// Toggleで表示するUIを切り替える
    /// </summary>
    public static void DrawProperties(MaterialProperty toggle, string keyword, MaterialEditor materialEditor, MaterialProperty[] properties){

        materialEditor.ShaderProperty (toggle, toggle.displayName);

        if (toggle.floatValue == 1f) {
            var subTexProps = properties
                .Where (x => x.name.Contains (keyword))
                .Where (x => x.name != toggle.name);

            foreach (var prop in subTexProps) {
                materialEditor.ShaderProperty (prop, prop.displayName);
            }
        }
    }

}

プロパティーから対象のUIを検索して表示しています.

参考

MaterialEditorはOldみたいです.