- Home /
Set another color of shader material color in a script?
I have a cloud shader and that shader have a white color, so i whant when i press a button my cloud shader color go slower to a another color that i put
Answer by xibanya · Jan 14, 2020 at 09:59 PM
Try this
using System;
using UnityEngine;
using System.Collections;
public class ColorBlend
{
public Renderer r;
public int materialIndex = 0;
public string property = "_Color";
[Space]
[Header("Debug")]
[SerializeField]
private float debugTime = 5;
[SerializeField]
private Color debugColor = new Color(0, 1, 1);
[SerializeField]
private bool debugSet;
private Coroutine blendRoutine;
void Update()
{
if (debugSet)
{
debugSet = false;
SetColor(debugColor, debugTime);
}
}
public void SetColor(Color newColor, float duration)
{
if (blendRoutine != null) StopCoroutine(blendRoutine);
blendRoutine = StartCoroutine(BlendRoutine(newColor, duration));
}
private IEnumerator BlendRoutine(Color endColor, float duration)
{
float elapsedTime = 0;
Color startColor = r.materials[materialIndex].GetColor(property);
while (elapsedTime < duration)
{
Color newColor = Color.Lerp(startColor, endColor, Mathf.Clamp01(elapsedTime / duration));
r.materials[materialIndex].SetColor(property, newColor);
elapsedTime += Time.deltaTime;
yield return null;
}
blendRoutine = null;
}
}
The main important part is using Lerp over time, and this is a pattern you can use over and over for a bunch of different things. Color.Lerp, Mathf.Lerp, Vector3.Lerp, Quaternion.Slerp etc all take 3 arguments. The first two represent opposite ends of a blend, the third argument is where, in between the first and second item, the blend should be, represented as 0-1, with 0.5 meaning a completely even blend. So when we divide elapsed time by duration, since we won't let elapsed time ever get bigger than duration, that will always result in a number between 0 and 1, making it perfect for use in a Lerp.
Your answer
![](https://koobas.hobune.stream/wayback/20220612221545im_/https://answers.unity.com/themes/thub/images/avi.jpg)