MaterialPropertyBlock

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

一、创建测试shader

  1. Shader "Unlit/Sphere"
  2. {
  3. Properties
  4. {
  5. _MainTex ("Texture", 2D) = "white" {}
  6. _Color("Color", Color) = (1,1,1,1)
  7. }
  8. SubShader
  9. {
  10. Tags { "RenderType"="Opaque" }
  11. LOD 100
  12.  
  13. Pass
  14. {
  15. CGPROGRAM
  16. #pragma vertex vert
  17. #pragma fragment frag
  18. // make fog work
  19. #pragma multi_compile_fog
  20. #include "UnityCG.cginc"
  21.  
  22. struct appdata
  23. {
  24. float4 vertex : POSITION;
  25. float2 uv : TEXCOORD0;
  26. };
  27.  
  28. struct v2f
  29. {
  30. float2 uv : TEXCOORD0;
  31. UNITY_FOG_COORDS(1)
  32. float4 vertex : SV_POSITION;
  33. };
  34.  
  35. sampler2D _MainTex;
  36. float4 _MainTex_ST;
  37. float4 _Color;
  38. v2f vert (appdata v)
  39. {
  40. v2f o;
  41. o.vertex = UnityObjectToClipPos(v.vertex);
  42. o.uv = TRANSFORM_TEX(v.uv, _MainTex);
  43. return o;
  44. }
  45. fixed4 frag (v2f i) : SV_Target
  46. {
  47. return _Color;
  48. }
  49. ENDCG
  50. }
  51. }
  52. }

二、创建测试脚本

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class SphereTest : MonoBehaviour {
  6.  
  7. public List<MeshRenderer> renders = new List<MeshRenderer>();
  8.  
  9. void Start () {
  10. for (int i = 0; i < renders.Count; i++)
  11. {
  12. //SetColor(renders[i]);
  13. SetColorPropertyBlock(renders[i]);
  14. }
  15. }
  16.  
  17. private void SetColor(MeshRenderer mr)
  18. {
  19. //这种方式会导致创建新的Material
  20. mr.material.color = new Color(Random.value, Random.value, Random.value);
  21. }
  22.  
  23. private void SetColorPropertyBlock(MeshRenderer mr)
  24. {
  25. //这种方式不会创建新的Material
  26. MaterialPropertyBlock properties = new MaterialPropertyBlock();
  27. properties.SetColor(
  28. "_Color", new Color(Random.value, Random.value, Random.value)
  29. );
  30. mr.SetPropertyBlock(properties);
  31. }
  32. }

三、创建测试场景

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

四、运行预览

5555.png

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

7777.png

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

6666.png

标签: Shader

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号