2

I have these lines of code in an update function in a C# Unity script:

variable1 = VALUE;
[I want to add a delay here]
variable 2 = VALUE;

I have tried Thread.Sleep(milliseconds) and Waitforseconds(). But I have had no luck in making them work.

It would be greatly appreciated if anyone could show me a solution to this problem.

Thanks, Isaac

Isaac Ljubic
  • 21
  • 1
  • 1
  • 5
  • Waitforseconds() must be in an iterator function that returns `IEnumerable` and uses `yield return`. Have you checked that? – Happypig375 Nov 26 '18 at 10:20

1 Answers1

6

Use WaitForSeconds() like yield WaitForSeconds(5); on your code. And take a look to Coroutines and WaitForSeconds(), there are good examples here.

using UnityEngine;
using System.Collections;
    
public class WaitForSecondsExample : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(Example());
    }

    IEnumerator Example()
    {
        print(Time.time);
        yield return new WaitForSeconds(5);
        print(Time.time);
    }
}

Lotan
  • 4,078
  • 1
  • 12
  • 30
  • 1
    I'm trying to figure this out and would like some help. I'm not really a programmer, but I have made a game in Unreal using blueprints. In blueprints there's a node simply called "delay", and it simply delays whatever comes after it for the amount of seconds you input in the node. I'm trying to figure out how to do exactly that in Unity, in C#. I came across this "WaitForSeconds", but I can't figure out how to use it. Where do I put the things that I want to execute after the delay? – Alexandre Marcati Jan 14 '22 at 18:40
  • 1
    @AlexandreMarcati you should try Bolt(Visual Scripting) on Unity(kind of similar to blueprints on unreal). There is a node called timer for that. – H_7 Feb 11 '22 at 04:12
  • Is there a way to use this timer function in C#? How does it work in code? – Alexandre Marcati Feb 11 '22 at 13:15