Jeremy McCloud
Jeremy McCloud

Reputation: 163

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

I would like to take the code in the Update method and delay it's execution by 2 or 3 seconds from when the application starts.

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);

}

}

The code is to slowly fade three lights in from my scene. Also, if there is better, more efficient way to code this, I'd be happy for any advice given!

Thank you!

Upvotes: 0

Views: 2022

Answers (2)

ARTAGE
ARTAGE

Reputation: 381

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;
   }
}

Upvotes: 0

mgear
mgear

Reputation: 1893

few options for simple delay:

  • using Invoke to delay setting 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
    
  • using CoRoutines and adding delay with : https://docs.unity3d.com/ScriptReference/WaitForSeconds.html

  • Increment separate timer variable inside Update loop, and check until its over 3secs

    float timer = 0;
    void Update()
    {
        timer += Time.deltaTime;
        if (timer>3)
        {
           //....
        }
    
  • Checking if (Time.time>3), returns time from start of game ://docs.unity3d.com/ScriptReference/Time-time.html *Maybe simplest for this, but note its time from start of whole game..

     void Update()
     {
         if (Time.time>3)
         {
             print(1);
         }
    

Upvotes: 2

Related Questions