Renderer rend = GetComponent<Renderer>();
rend.material.mainTexture = textures;
แต่หากเราทำการเขียน Shader เองเราจะต้องเรียก function ในการ Set Property สำหหรับค่านั้นๆ
เริ่มกันเลยครับ
1. เตรียมไฟล์ Shader ที่ต้องการ จากตัวอย่างจะเป็น Shader ที่
Shader "TonyShader/AnimatedUV"
{
Properties
{
_TextureSample0("Texture Sample 0", 2D) = "white" {}
_YSpeed("YSpeed", Range(0 , 1)) = 2
_XSpeed("XSpeed", Range(0 , 1)) = 2
}
SubShader
{
Tags{ "RenderType" = "Opaque" "Queue" = "Geometry+0" }
Cull Back
CGPROGRAM
#include "UnityShaderVariables.cginc"
#pragma surface surf Standard vertex:vertexDataFunc
struct Input
{
float2 texcoord_0;
};
uniform sampler2D _TextureSample0;
uniform float _XSpeed;
uniform float _YSpeed;
void vertexDataFunc(inout appdata_full v, out Input o)
{
UNITY_INITIALIZE_OUTPUT(Input, o);
float4 appendResult27 = float4((_Time.y * _XSpeed) , (_Time.y * _YSpeed) , 0 , 0);
o.texcoord_0.xy = v.texcoord.xy * float2(1,1) + appendResult27.xy;
}
void surf(Input i , inout SurfaceOutputStandard o)
{
o.Albedo = tex2D(_TextureSample0,i.texcoord_0).xyz;
o.Alpha = 1;
}
ENDCG
}
Fallback "Diffuse"
}
using UnityEngine;
public class ShaderController : MonoBehaviour
{
private Renderer render;
private bool isAnimate;
private float speed;
void Start()
{
// ใช้สำหรับอ้างอิงตัวแปร Renderer
render = GetComponent<Renderer>();
}
void Update()
{
// รับค่า Input เพื่อเปิด / ปิด UV Animation
if (Input.GetKeyDown(KeyCode.Space))
{
isAnimate = !isAnimate;
speed = isAnimate ? 1 : 0;
}
// Function ที่ใช้ในการ Set Property ซึ่งสามารถ Set Property อื่นๆได้ เช่น
// SetTexture(), SetColor(), อื่นๆ
render.material.SetFloat("_YSpeed", speed);
render.material.SetFloat("_XSpeed", speed);
}
}
เพียงเท่านี้ก็สามารถนำไปประยุกต์ใช้งานได้แล้วครับ
NO GAME NO DREAM !!!!