- Home /
why doesn't the background color of my camera change
i'm trying to make a day and night cycle in unity. I managed to get the background color of my camera to change from black(Night) to blue(day) slowly in the morning but I try to change it back to black in the afternoon it doesn't work. What am I doing wrong?
public class GameWorld : MonoBehaviour {
public float igametime;
public GameObject moon;
public GameObject sun;
public Camera mainCamera;
public Vector4 SkyColour;
public int gametimeSpeed;
public void Start()
{
sun.light.enabled = false;
moon.light.enabled = false;
}
public void Update()
{
igametime = Time.time * gametimeSpeed;
while (igametime > 1440)
igametime -= 1440;
sun.transform.Rotate( new Vector3(0.2f, 0, 0) * Time.deltaTime * gametimeSpeed);
moon.transform.Rotate(new Vector3(0.333333f, 0, 0) * Time.deltaTime * gametimeSpeed);
// Dawn (this works)
if (igametime > 0 && igametime <= 60)
{
sun.light.enabled = false;
moon.light.enabled = false;
SkyColour = new Vector4(0.0105f, 0.0110f, 0.0176f, 0) *igametime;
mainCamera.backgroundColor = SkyColour;
}
// Day
else if (igametime > 60)
{
sun.light.enabled = true;
moon.light.enabled = false;
}
// Dusk (this dosen't work)
else if (igametime > 960 && igametime <= 1020)
{
sun.light.enabled = false;
moon.light.enabled = false;
mainCamera.backgroundColor = new Vector4(0.63f - 0.0105f * (igametime - 960), 0.66f - 0.0110f * (igametime - 960),
1.056f - 0.0176f * (igametime - 960), 1) ;
}
// Night
else if (igametime > 1020 && igametime <= 1440)
{
sun.light.enabled = false;
moon.light.enabled = true;
}
else
{
moon.light.enabled = false;
sun.light.enabled = false;
}
As a side note - I would change this code:
igametime = Time.time * gametimeSpeed;
while (igametime > 1440)
igametime -= 1440;
to:
igametime += Time.time * gametimeSpeed;
if (igametime > 1440)
igametime -= 1440;
In your implementation, changing gametimeSpeed at runtime, can result in instant daytime change. For example, if Time.time is equal to 600 and speed is 1, changing speed to 2 will cause instant jump from day to night (1200).
Answer by ArkaneX · Sep 24, 2013 at 11:01 AM
I doesn't work, because when your igametime variable is greater than 60, then you always end up in the first else (Day). You need to change it to:
else if (igametime > 60 && igametime <= 960)
Your answer
![](https://koobas.hobune.stream/wayback/20220613114727im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How would I make a ListChangedEvent? 1 Answer
Problem with rotation Please Help Me 1 Answer
I have a problem with coins 1 Answer