MaterialPropertyBlock

作者:追风剑情 发布于:2018-9-21 16:19 分类:Shader

一、创建测试shader

Shader "Unlit/Sphere"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
		_Color("Color", Color) = (1,1,1,1)
	}
	SubShader
	{
		Tags { "RenderType"="Opaque" }
		LOD 100

		Pass
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			// make fog work
			#pragma multi_compile_fog
			
			#include "UnityCG.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float2 uv : TEXCOORD0;
			};

			struct v2f
			{
				float2 uv : TEXCOORD0;
				UNITY_FOG_COORDS(1)
				float4 vertex : SV_POSITION;
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;
			float4 _Color;
			
			v2f vert (appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = TRANSFORM_TEX(v.uv, _MainTex);
				return o;
			}
			
			fixed4 frag (v2f i) : SV_Target
			{
				return _Color;
			}
			ENDCG
		}
	}
}

二、创建测试脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SphereTest : MonoBehaviour {

    public List<MeshRenderer> renders = new List<MeshRenderer>();

	void Start () {
        for (int i = 0; i < renders.Count; i++)
        {
            //SetColor(renders[i]);
            SetColorPropertyBlock(renders[i]);
        }
	}

    private void SetColor(MeshRenderer mr)
    {   
        //这种方式会导致创建新的Material
        mr.material.color = new Color(Random.value, Random.value, Random.value);
    }

    private void SetColorPropertyBlock(MeshRenderer mr)
    {
        //这种方式不会创建新的Material
        MaterialPropertyBlock properties = new MaterialPropertyBlock();
        properties.SetColor(
            "_Color", new Color(Random.value, Random.value, Random.value)
        );
        mr.SetPropertyBlock(properties);
    }
}

三、创建测试场景

放三个小球,挂上同一个材质球。

四、运行预览

5555.png

SetColor()方法设置小球颜色,会导致创建新的材质实例

7777.png

SetColorPropertyBlock()方法设置小球颜色不会创建新的材质实例

6666.png

标签: Shader

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号