在淡入这些灯之前,如何在 Unity C# 中添加两秒的延迟?

How can I add a two second delay in Unity C#, before I fade these lights in?

我想获取 Update 方法中的代码,并在应用程序启动后将其执行延迟 2 或 3 秒。

public class LightController : MonoBehaviour {
public Light Light_01;
public Light Light_02;
public Light Light_03;
public float smoothValue;

// Use this for initialization
void Start () {
    Light_01.intensity = 0;
    Light_02.intensity = 0;
    Light_03.intensity = 0;

}

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


    if (Light_01.intensity <= 8)
        Light_01.intensity += Time.deltaTime * smoothValue;
    if (Light_02.intensity <= 5)
        Light_02.intensity += Time.deltaTime * (smoothValue / 2);
    if (Light_03.intensity <= 1.8)
        Light_03.intensity += Time.deltaTime * (smoothValue / 3);

}

}

代码是从我的场景中慢慢淡入三盏灯。另外,如果有更好、更有效的编码方式,我很乐意提供任何建议!

谢谢!

简单延迟的几个选项:

  • 使用调用来延迟设置 bool : https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html

    bool isRunning = false;
    void Start()
    {
        Invoke("StartFader", 3);
    }
    
    void StartFader()
    {
        isRunning = true;
    }
    
    void Update()
    {
        if (!isRunning) return; // early exit
    
  • 使用 CoRoutines 并添加延迟:https://docs.unity3d.com/ScriptReference/WaitForSeconds.html

  • 在更新循环中增加独立的定时器变量,并检查直到它超过 3 秒

    float timer = 0;
    void Update()
    {
        timer += Time.deltaTime;
        if (timer>3)
        {
           //....
        }
    
  • 检查是否 (Time.time>3), returns 从游戏开始的时间 ://docs.unity3d.com/ScriptReference/Time-time.html *这可能是最简单的,但请注意它从整个游戏开始的时间..

     void Update()
     {
         if (Time.time>3)
         {
             print(1);
         }
    
float time = .0f;

void Start () 
{
    Light_01.intensity = 0;
    Light_02.intensity = 0;
    Light_03.intensity = 0;
}

void Update()
{
if (time <= 2.0f)
   {
    time += Time.deltaTime
    Light_01.intensity = time;
    Light_02.intensity = time;
    Light_03.intensity = time;
   }
}