I am trying to smoothly change the camera's background color between two colors that are picked randomly. I've already achieved that, but then I started noticing that there is a flash whenever a new color is picked. I've uploaded a video of the problem on this link. And this is the script that I'm currently using:
public Color color1;
public Color color2;
float time;
float time2;
float transition;
int firstColor = 0;
void Update()
{
if (firstColor == 0)
{
color1 = Random.ColorHSV(Random.value, Random.value);
color2 = Random.ColorHSV(Random.value, Random.value);
firstColor = 1;
}
Camera.main.backgroundColor = Color.Lerp(color2, color1, transition);
time += Time.deltaTime;
time2 += Time.deltaTime;
transition = time2 / 5;
if (time > 5)
{
color2 = color1;
color1 = Random.ColorHSV(Random.value, Random.value);
time = 0;
time2 = 0;
}
}
Any help is very much appreciated.
You need to do this with a coroutine. You can then easily be able to program when to change new color after the current transition ends. Anything you have to do overtime, you should always consider using coroutines. It removes the needs for lot's of boolean variable and confusion.
You can wait in a coroutine function without a boolean variable but you can't in a void function like the Update
function. You are already using Time.deltaTime
and the Lerp
function so you know what you are doing half way. Here is a proper way to do this:
//2 seconds within each transition/Can change from the Editor
public float transitionTimeInSec = 2f;
private bool changingColor = false;
private Color color1;
private Color color2;
void Start()
{
StartCoroutine(beginToChangeColor());
}
IEnumerator beginToChangeColor()
{
Camera cam = Camera.main;
color1 = Random.ColorHSV(Random.value, Random.value);
color2 = Random.ColorHSV(Random.value, Random.value);
while (true)
{
//Lerp Color and wait here until that's done
yield return lerpColor(cam, color1, color2, transitionTimeInSec);
//Generate new color
color1 = cam.backgroundColor;
color2 = Random.ColorHSV(Random.value, Random.value);
}
}
IEnumerator lerpColor(Camera targetCamera, Color fromColor, Color toColor, float duration)
{
if (changingColor)
{
yield break;
}
changingColor = true;
float counter = 0;
while (counter < duration)
{
counter += Time.deltaTime;
float colorTime = counter / duration;
Debug.Log(colorTime);
//Change color
targetCamera.backgroundColor = Color.Lerp(fromColor, toColor, counter / duration);
//Wait for a frame
yield return null;
}
changingColor = false;
}