这里给出一个在 Unity 中实现昼夜亮度变化的简单示例,思路是通过协程周期性地调整场景中 Light 组件的 intensity,让光照强度在 0 到 1 之间循环过渡,从而模拟白天与黑夜的切换。

实现思路

  • Start 中启动一个协程 SyncLight,负责驱动整个昼夜循环。
  • 协程内部用两个 for 循环分别完成由亮到暗(白天到黑夜)和由暗到亮(黑夜到白天)的过渡。
  • 每次循环结束后,协程再次启动自身,形成持续往复的昼夜变化。
  • 额外提供 OnUIDayNight 接口,允许通过 UI 开关打开或关闭昼夜循环,并在关闭时把亮度重置回默认值。

示例代码

using UnityEngine;
using System.Collections;

/// <summary>
/// @brief  is for weather system
/// </summary>
public class WeatherSystem : MonoBehaviour
{
    [SerializeField]
    private Light light;
    private float _current_intensity = 1.0f;


    // Use this for initialization
    void Start()
    {
        StartCoroutine(SyncLight());


    }

    // Update is called once per frame
    void Update()
    {

    }



    IEnumerator SyncLight()
    {
        yield return new WaitForSeconds(10.0f);

        for (; _current_intensity >= 0; _current_intensity -= 0.01f)
        {
            yield return new WaitForSeconds(1);
            light.GetComponent<Light>().intensity = _current_intensity;

        }

        yield return new WaitForSeconds(5.0f);

        for (_current_intensity = 0.0f; _current_intensity <= 1; _current_intensity += 0.01f)
        {
            yield return new WaitForSeconds(1);
            light.GetComponent<Light>().intensity = _current_intensity;

        }

        StartCoroutine(SyncLight());

    }


    public void OnUIDayNight(bool _is)
    {
        if (_is)
        {

            StopAllCoroutines();
            StartCoroutine(SyncLight());
        }
        else
        {
            StopAllCoroutines();
        }
        light.GetComponent<Light>().intensity = 1.0f;

    }
}