UnityGameProjectsCode / AbandondedGame / DayNightCycle.cs
DayNightCycle.cs
Raw
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DayNightCycle : MonoBehaviour
{
    public float fullCycleTime; //determines how long the day night transition takes
    private float timeSinceStart;
    private float lerpTime;
    private Vector3 startingRotation;
    private Vector3 endingRotation;
    private bool cycleStarted;
    private Light sun;

    private void Awake()
    {
        startingRotation = transform.rotation.eulerAngles;
        endingRotation = transform.rotation.eulerAngles;
        endingRotation.x = 0.0f;
        sun = GetComponent<Light>();
    }

    private void Update()
    {
        if(cycleStarted)
        {
            timeSinceStart += Time.deltaTime;

            if (timeSinceStart < fullCycleTime)
            {
                lerpTime = Mathf.InverseLerp(0, fullCycleTime, timeSinceStart);

                Vector3 lerpMovement = Vector3.Lerp(startingRotation, endingRotation, lerpTime);
                float lerpIntensity = Mathf.Lerp(1, 0.1f, lerpTime);

                sun.intensity = lerpIntensity;
                transform.rotation = Quaternion.Euler(lerpMovement);
            }
            else
            {
                lerpTime = 1.0f;
            }
        }
    }

    public float GetLerpTime()
    {
        return lerpTime;
    }

    public void SetCycleStarted(bool state)
    {
        cycleStarted = state;
    }

    public void OnGameReset()
    {
        timeSinceStart = 0.0f;
        lerpTime = 0.0f;
        sun.intensity = 1.0f;
        transform.rotation = Quaternion.Euler(startingRotation);
    }
}