Quest: Hide & Seek Coroutines Quest
Challenge: Time Of Day
Feel free to share your solutions, ideas and creations below. If you get stuck, you can find some ideas here for completing this challenge.
Quest: Hide & Seek Coroutines Quest
Challenge: Time Of Day
Feel free to share your solutions, ideas and creations below. If you get stuck, you can find some ideas here for completing this challenge.
Here is a solution using lerp.
using System.Collections;
using UnityEngine;
public class DayNightCycler : MonoBehaviour
{
// configs
[SerializeField] float secondsOfDay = 10f;
[SerializeField] float secondsOfNight = 10f;
[SerializeField] float maxSkyboxExposure = 2f;
[SerializeField] float minSkyboxExposure = .25f;
[SerializeField] float transitionSpeed = .5f;
// Unity messages
IEnumerator Start()
{
while (true)
{
yield return new WaitForSeconds(secondsOfDay);
yield return StartCoroutine(TransitionToNight());
yield return new WaitForSeconds(secondsOfNight);
yield return StartCoroutine(TransitionToDay());
}
}
// private methods
IEnumerator TransitionToNight()
{
float interpolator = 1f;
while (CurrentSkyboxExposure() > minSkyboxExposure)
{
interpolator -= transitionSpeed * Time.deltaTime;
float newExposure = Mathf.Lerp(minSkyboxExposure, maxSkyboxExposure, interpolator);
SetSkyboxExposure(newExposure);
yield return null;
}
}
IEnumerator TransitionToDay()
{
float interpolator = 0f;
while (CurrentSkyboxExposure() < maxSkyboxExposure)
{
interpolator += transitionSpeed * Time.deltaTime;
float newExposure = Mathf.Lerp(minSkyboxExposure, maxSkyboxExposure, interpolator);
SetSkyboxExposure(newExposure);
yield return null;
}
}
float CurrentSkyboxExposure()
{
return RenderSettings.skybox.GetFloat("_Exposure");
}
void SetSkyboxExposure(float value)
{
RenderSettings.skybox.SetFloat("_Exposure", value);
}
}