| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 |
- using UnityEngine;
- namespace _Scripts
- {
- public class DayNightCycle : MonoBehaviour
- {
- [Header("References")]
- [SerializeField] private Light sun;
- [SerializeField] private Material skyboxMaterial;
- [Header("Cycle Settings")]
- [SerializeField] private float dayLengthInMinutes = 4f;
- private float timeOfDay = 0.5f; // 0 → 1
- private static readonly int Rotation = Shader.PropertyToID("_Rotation");
- private static readonly int Exposure = Shader.PropertyToID("_Exposure");
- void Update()
- {
- // Advance time
- timeOfDay += Time.deltaTime / (dayLengthInMinutes * 60f);
- if (timeOfDay > 1f) timeOfDay = 0f;
- UpdateSun();
- UpdateSkybox();
- }
- void UpdateSun()
- {
- float sunAngle = timeOfDay * 360f - 90f;
- sun.transform.rotation = Quaternion.Euler(sunAngle, 170f, 0);
- // Dim light at night
- float intensity = Mathf.Clamp01(Mathf.Sin(timeOfDay * Mathf.PI));
- sun.intensity = intensity * 1.2f;
- }
- void UpdateSkybox()
- {
- skyboxMaterial.SetFloat(Rotation, timeOfDay * 360f);
- float exposure = Mathf.Clamp(Mathf.Sin(timeOfDay * Mathf.PI), 0.15f, 1f);
- skyboxMaterial.SetFloat(Exposure, exposure);
- }
- }
- }
|