TimeChanger.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using UnityEngine;
  2. namespace _Scripts
  3. {
  4. public class DayNightCycle : MonoBehaviour
  5. {
  6. [Header("References")]
  7. [SerializeField] private Light sun;
  8. [SerializeField] private Material skyboxMaterial;
  9. [Header("Cycle Settings")]
  10. [SerializeField] private float dayLengthInMinutes = 4f;
  11. private float timeOfDay = 0.5f; // 0 → 1
  12. private static readonly int Rotation = Shader.PropertyToID("_Rotation");
  13. private static readonly int Exposure = Shader.PropertyToID("_Exposure");
  14. void Update()
  15. {
  16. // Advance time
  17. timeOfDay += Time.deltaTime / (dayLengthInMinutes * 60f);
  18. if (timeOfDay > 1f) timeOfDay = 0f;
  19. UpdateSun();
  20. UpdateSkybox();
  21. }
  22. void UpdateSun()
  23. {
  24. float sunAngle = timeOfDay * 360f - 90f;
  25. sun.transform.rotation = Quaternion.Euler(sunAngle, 170f, 0);
  26. // Dim light at night
  27. float intensity = Mathf.Clamp01(Mathf.Sin(timeOfDay * Mathf.PI));
  28. sun.intensity = intensity * 1.2f;
  29. }
  30. void UpdateSkybox()
  31. {
  32. skyboxMaterial.SetFloat(Rotation, timeOfDay * 360f);
  33. float exposure = Mathf.Clamp(Mathf.Sin(timeOfDay * Mathf.PI), 0.15f, 1f);
  34. skyboxMaterial.SetFloat(Exposure, exposure);
  35. }
  36. }
  37. }