How to cycle through color spectrum with material?

Hi, i was wondering if anyone new the code to cycle through colors in c# code. I have tried Color.Lerp, but had no luck. If you have done this, some code snipits would be much apreciated, thanks! This is what I have so far, and I don’t know why it doesn’t work.

using UnityEngine;
using System.Collections;

public class colorchang : MonoBehaviour {

public Color colors = new Color[0];

public int currentIndex = 0;

public int changeColourTime = 1;

private float lastChange = 0.0f;

void Update()
{

if (colors.Length > 0 && lastChange + changeColourTime < Time.time)
{
    lastChange = Time.time;
    currentIndex = (currentIndex + 1) % colors.Length;
				
    renderer.material.color = Color.Lerp (colors[currentIndex], colors[currentIndex + 1], Time.time );
}

}
}

Do you want a different color from an array of colors each frame, or do you want to gradually change colors from one color index to the next, changing to the next index when last Lerp() is done?

http://wiki.unity3d.com/index.php/Fade

1 Answer

1

I’m making a few assumptions about what you want. I’m assuming you want an array of colors, and that you Lerp between two entries in the array in ‘changeColourTime’. Moving to the forward in the array and starting a new Lerp() when that fade is done:

using UnityEngine;
using System.Collections;

public class ColorChange : MonoBehaviour {

	public Color[] colors;
		
	public int currentIndex = 0;
	private int nextIndex;
	
	public float changeColourTime = 2.0f;
	
	private float lastChange = 0.0f;
	private float timer = 0.0f;
	
	void Start() {
		if (colors == null || colors.Length < 2)
			Debug.Log ("Need to setup colors array in inspector");
		
		nextIndex = (currentIndex + 1) % colors.Length;	
	}
	
	void Update() {
		
		timer += Time.deltaTime;
		
		if (timer > changeColourTime) {
			currentIndex = (currentIndex + 1) % colors.Length;
			nextIndex = (currentIndex + 1) % colors.Length;
			timer = 0.0f;
			
		}
		renderer.material.color = Color.Lerp (colors[currentIndex], colors[nextIndex], timer / changeColourTime );
	}
}

Hey, thanks a bunch, thats a smart solution!