Hey, I’ve made this script tho I’m having a little problem with it, doesn’t change colors for some reason
public Color[] bgColors;
private float t = 0.05f;
private Renderer rend;
// Use this for initialization
void Awake()
{
rend = GetComponent<Renderer>();
}
void Start ()
{
Invoke ("changeColor", 1f);
}
// Update is called once per frame
void Update () {
}
void changeColor()
{
Debug.Log ("IM HERE");
Color.Lerp(rend.material.color, bgColors[Random.Range(0, bgColors.Length)],t);
Invoke ("changeColor", 1f);
}
First, If you don’t change the value of “t” you’ll always get the same color from Color.Lerp. Check again the documentation of Color.Lerp, the “t” value should go from 0 to 1 to get the proper transition: Unity - Scripting API: Color.Lerp
Second, Lerp returns a color, it doesn’t change the one you provided, so you have to use the returned color for something. Again, look at the docs.
Third, I don’t understand what you’re trying to do, but I guess you’re also confused about the Invoke method.
If you want to lerp from one color to another and want the transition to last 1 second you have to update the color on every frame. Your “Invoke(“changeColor”,1f);” line calls the changeColor only once every second.
Also, you’re changing the second color to a random color for the list on every call to that function, that would give really weird results.
I’ll make a guess here, I think you want this code:
public Color[] bgColors;
private Renderer rend;
// Use this for initialization
void Awake()
{
rend = GetComponent<Renderer>();
}
void Start ()
{
StartCoroutine(changeColor());
}
IEnumerator changeColor()
{
Color startColor = rend.material.color;
Color endColor = bgColors[Random.Range(0, bgColors.Length)];
float t = 0f;
while(t <= 1f) {
rend.material.color = Color.Lerp(startColor,endColor,t);
t += Time.deltaTime;
yield return null;
}
StartCoroutine(changeColor());
}
Color.Lerp(Color a, Color b, float t)
returns a new Color. To change one of the passed colors you have to assign to the passed color, i.e.
rend.material.color=Color.Lerp(rend.material.color, bgColors[Random.Range(0, bgColors.Length)],t);