C#控制shader———Alpha渐变以及Color的两个颜色之间互转
直接挂在有材质球的物体上就可以用,代码简单实用,多多指教
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum ShderType
{
Alpha来回波动 = 0,颜色之间互相转换 = 1
}
public class ShaderPlayCortroller : MonoBehaviour {
public ShderType SType = ShderType.Alpha来回波动;
private Renderer _render;
private float num = 0f;
[Header("控制shader颜色Alpha来回波动")]
[Tooltip("输入需要控制的shader颜色名字")]
public string ShaderColorName = "_TintColor";
public float AlphaSpeed = 1f;
public float MaxAlpha = 0.2f;
public float MinAlpha = 0f;
bool IsRange = false;
bool IsRangeOne = false;
[Header("控制shader颜色之间互相转换")]
[Tooltip("第一个颜色")]
public Color colorFirst = Color.white;
[Tooltip("第二个颜色")]
public Color colorTwo = Color.red;
Color colorRange ;
[Tooltip("数值越大渐变越慢")]
public float ColorChangeSpeed = 5f;
// Use this for initialization
void Start () {
_render = GetComponent<Renderer>();
IsRange = true;
}
// Update is called once per frame
void Update () {
switch (SType)
{
case ShderType.Alpha来回波动:
AlphaChange();
break;
case ShderType.颜色之间互相转换:
ColorChange();
break;
default:
break;
}
}
void AlphaChange()
{
if (IsRange == true)
{
num = Mathf.MoveTowards(num, MaxAlpha, Time.deltaTime * AlphaSpeed);
_render.material.SetColor(ShaderColorName, new Color(1, 1, 1, num));
if (num >= MaxAlpha - 0.01f)
{
IsRangeOne = true;
IsRange = false;
}
}
if (IsRangeOne == true)
{
num = Mathf.MoveTowards(num, MinAlpha, Time.deltaTime * AlphaSpeed);
_render.material.SetColor(ShaderColorName, new Color(1, 1, 1, num));
if (num <= MinAlpha + 0.01f)
{
IsRange = true;
IsRangeOne = false;
}
}
}
void ColorChange()
{
float a = Mathf.PingPong(Time.time, ColorChangeSpeed) / ColorChangeSpeed;
colorRange = Color.LerpUnclamped(colorFirst, colorTwo, a);
_render.material.color = colorRange;
}
}