通过再脚本中修改材质参数,可以实现游戏中动态更新材质表现(如修改颜色),下面是一个在每一帧随机更改材质颜色的简单实例。
1、创建一个Standard Surface Shader,命名为TestShader,
文本编辑器打开将内容换成下列代码
Shader "Custom/TestShader"{Properties{_Color ("Color", Color) = (1,1,1,1)_MainTex ("Texture", 2D) = "white" { }}SubShader{Tags { "RenderType"="Opaque" }CGPROGRAM#pragma surface surf Standardsampler2D _MainTex;struct Input{float2 uv_MainTex;};fixed4 _Color;void surf (Input IN, inout SurfaceOutputStandard o){fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;o.Albedo = c.rgb;}ENDCG}FallBack "Diffuse"}
该Shader有_Color和_MainTex两个属性,在脚本中就是通过修改这两个属性分别设置材质的颜色和贴图。
2、在TestShader上右键创建Material,命名为TestMaterial
场景中有一个球体和立方体,将TestMaterial分别拖到这两个物体上,默认显示为白色。
3、创建一个脚本文件ChangeMaterial.cs用于修改材质属性,脚本代码如下
using System.Collections;using System.Collections.Generic;using UnityEngine;public class ChangeMaterial : MonoBehaviour{// Start is called before the first frame updatevoid Start(){Random.InitState((int)System.DateTime.Now.Ticks);//初始化随机种子var texture = Resources.Load<Texture>("Rock");//加载Resources目录下的Rock贴图gameObject.GetComponent<Renderer>().material.SetTexture("_MainTex",texture);//Material.SetTexture设置贴图属性}// Update is called once per framevoid Update(){Color color = new Color(Random.value, Random.value, Random.value);//生成随机颜色gameObject.GetComponent<Renderer>().material.SetColor("_Color", color);//Material.SetColor设置颜色属性}}
在球体和立方体上添加该脚本组件,运行后效果