C# change light color every few seconds

Hello,

I have an object and this object has a child(cubeLight). I need to change this light from the color blue to red every few seconds. so it changes to blue and back to red and back to blue etc. my code only changes it once and I have no idea why.

my code: `

public float resetTime = 0.5f;

public Light cubeLight;

void Awake()
{
	StartCoroutine("GoBlue");
}

IEnumerator GoBlue()
{
	while(true)
	{
	cubeLight.color = Color.blue;
		Debug.Log("blue");
	yield return new WaitForSeconds(resetTime);
	}

}

}`

in the awake function you ask it to change to blue you never change it to red or anything else from there out.

Two ways, either you use the update or you use a coroutine that never ends. The rest is just a timer.

In Update:

var timer:float;
Color[] color = new Color[2];
int index = 0;
function Start(){
    color[0] = Color.blue;
    color[1] = Color.red;
    cubeCoor = color[index];
}

function Update(){
    timer += Time.deltaTime;
    if(timer > 2){
        if(++index == color.Length)index = 0;
        cubeColor = color[index];
        timer = 0;
    }
} 

Coroutine:

function CoroutineChanger(){
   var timer :float;
   while(true){
      while(timer < 2){
         yield;
      }
      if(++index == color.Length)index = 0;
      cubeColor = color[index];
      timer = 0;
   }
}

Same, same but different.

Put this script to the object where the material is that you want to change color. Then put on the colorA and colorB the colors you want it to change. If you want to change the speed you can do something like "public float speed = 1.0F; " i guess. colorMaterial needs to be the name of the material you want to use. Also the “_Color” might be needed to change depending what the color is named on you shader.

using UnityEngine;
using System.Collections;

public class ChangeColor : MonoBehaviour {

    public Color colorA;
    public Color colorB;
    public float speed;
    public Material colorMaterial;

	void Update () {
        Color color = Color.Lerp(colorA, colorB, Mathf.PingPong(Time.time * speed, 1));
        colorMaterial.SetColor("_Color", color);
	}
}