Adding a dynamic day and night cycle to your game can really add depth, immersion, and even realism to the player experience in many games. If you’re creating a survival game or open-world adventure or just looking to improve the atmosphere of your game, adding a day-night cycle in Unity can be quite valuable to take your game to the next level.
In this article, we’ll outline a step-by-step guide on how to create a basic day and night cycle in Unity. By the end, you’ll be able to have changing lighting and environmental effects dynamically, for a smooth transition from day to night.
Why Add a Day and Night Cycle?
A day and night cycle is a precious addition to your game should time-based mechanics or its immersion be very crucial. Here’s why adding that feature might do a lot of good to your game:
- Atmosphere & Realism: The changing lighting conditions can lend an organic sense of life and activity to your game space.
- Gameplay Mechanics: Some games change enemy difficulty, visibility, or other mechanics tied to the time of day.
- Strategic Elements: At certain times of day, the player may need to collect resources or fulfill objectives.
Getting Familiar with the Concept: What Will We Do?
In Unity, a day and night cycle typically involves adjusting the following:
- Light source: Simulating the movement of the sun and moon.
- Ambient light: Changing how bright or dark the overall environment is.
- Skybox: Updating the sky’s visuals to match the time of day (bright for day, dark and starry for night).
- Post-processing: Optionally, changing visual effects like bloom and contrast to emphasize the cycle.
Now, let’s break down how to implement these in Unity.
Step 1: Setup of the Light Source
First create a directional light. This will be your sun. In Unity, a directional light corresponds to your sunlight because it spreads out evenly across your entire scene.
1.1 Creating the Sun Object
- In the editor of Unity, right-click in the Hierarchy panel.
- Select Light > Directional Light.
- Name this object Sun for clarity.
1.2 Light Properties
- Under the Light properties, set the Intensity of your sun to something reasonable, perhaps 1.5.
- Change the color of the light to soft yellowish to simulate daylight.
So you have created a sun, but it is stationary. We wish to create it to rotate across the sky to model how the sun moves from sunrise through to sunset.
2 Creating the Sun’s Rotation
The next task is to create a script to rotate the sun over time which in turn simulates a day-night cycle.
2.1 The SunRotation Script
Create a new C# script called DayNightCycle.cs and attach it to your Sun object. Here’s how you can get the basic rotation set up:
using UnityEngine;
public class DayNightCycle : MonoBehaviour
{
public float dayDuration = 120f; // Duration of a full day in seconds
private float rotationSpeed;
void Start()
{
// Calculate rotation speed based on day duration
rotationSpeed = 360f / dayDuration;
}
void Update()
{
// Rotate the sun
transform.Rotate(Vector3.right, rotationSpeed * Time.deltaTime);
}
}2.2 What’s Going On Here?
- We’re moving in orbit around the sun along the X-axis .
- dayDuration lets you decide how long one day (in seconds) should last. You can set this to whatever speed you’d like your day/night cycle to be at.
- The rotationSpeed is really a function of the total amount of time passed over a day. The sun orbits 360 degrees throughout this time.
Step 3: Fiddling with Ambient Light and Color
Ambient light in the scene should fade out as the sun sets and vice versa when it rises. This indicates a need for dynamic adjustments of the ambient light of the environment.
3.1 Ambient Light Control
Change the DayNightCycle script to take care of the ambient lights as well based on the sun’s rotation.
using UnityEngine;
public class DayNightCycle : MonoBehaviour
{
public float dayDuration = 120f;
public Gradient ambientColors;
private float rotationSpeed;
private Light sun;
void Start()
{
rotationSpeed = 360f / dayDuration;
sun = GetComponent<Light>();
}
void Update()
{
// Rotate the sun
transform.Rotate(Vector3.right, rotationSpeed * Time.deltaTime);
// Adjust ambient lighting
float timeFactor = Mathf.InverseLerp(-90, 90, transform.eulerAngles.x);
RenderSettings.ambientLight = ambientColors.Evaluate(timeFactor);
}
}3.2 Ambient Colors
You can use the Gradient ambientColors to define an ambient color that transitions based on the time of day. You could create a gradient that is bright blue in the daytime, graduating into dark purple or black at night.
Here, you’re controlling how the light intensity varies with the sun position via the timeFactor.
You can fine-tune the gradient in Unity Editor to suit the mood of your game by modifying the ambientColors inside the Inspector.
Step 4: Skybox and Post-Processing Effects
4.1 Changing the Skybox
Skybox material in Unity illustrates the background of the sky. It is possible to change the skybox for day and night:
- Day Skybox: Bright cloud-filled skybox.
- Night Skybox: A starry or dark sky texture.
Use the RenderSettings.skybox property to switch skyboxes depending on the time of day. Here’s an example:
if (isDayTime)
{
RenderSettings.skybox = daySkybox;
}
else
{
RenderSettings.skybox = nightSkybox;
}4.2 Adding additional effects post-processing
Utilize Unity’s Post-Processing Stack to obtain more dramatic transitions. Add effects like bloom or exposure adjustments that may change with the time of day. For example, you may reduce the brightness a little during nighttime and set a soft glow effect in sunset.
Step 5: Adding a Moon for Nighttime
Now you have the sun lit up, so use this opportunity to create your second Directional Light, where you alternate between letting the sun and moon be active states based upon the time of day.
- Create another directional light for the moon.
- Adjust the light color on the moon to much dimmer, say, 0.3 intensity.
- Now toggle between your sun and your moon inside the code with the sun’s angle determining which one is active.
if (sunAngle > 180)
{
moonLight.enabled = true;
sunLight.enabled = false;
}
else
{
moonLight.enabled = false;
sunLight.enabled = true;
}Step 6: Fine-Tuning and Customization
Once you have the basics up and running, you can add advanced features like:
- Dynamic shadows: You can change strength of shadows by the passing of time.
- Weather Effects: Rain or fog depending on time of day.
- Gameplay Triggers: Create events which only happen at specific times. This should be familiar from for example: Zombies only come out at night!.
These settings can be played around with, the length of day and night adjusted, the intensity of lights changed, or color settings changed to suit one’s needs to create the desired atmosphere.
Conclusion
Adding day and night cycles to a Unity game brings life into the game world, which is imperative for good gameplay. Whether your goal is to have a simple aesthetic effect or to over time develop your gameplay, the following principles should be solid ground for you. From here, you can add a lot of complexity on top of this system and add things that uniquely suit your game’s needs.
Before the end of this tutorial, you will be well on your way to a seamless day-night transition, with sun and moon rotation, ambient light changes, and skybox updates. This is a pretty basic system you can customize to your game’s feel and mechanics, giving you endless opportunities for development.
More Tips:
- Playtesting: Always playtest your day-night cycle across different hardware to ensure smooth performance.
- Lighting Profiles: You can also save different lighting profiles so that in a day scene you can have one amount of lighting and quickly switch to another in a night scene, or whatever serves your artwork.
By following these steps, you’ll create an immersive, visually appealing day-night cycle that sets your game apart from the competition!