• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity
×
 

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel
    • Ask a question
    • Spaces
    • Home /
    avatar image
    11
    Question by Jan_Julius · Sep 24, 2014 at 01:39 PM · timedelay

    [c#] How can I let something happen after a small delay?

    How can I add a small delay between things happening in a function, after the delay it should continue with what it was doing? in C#

    Add comment · Show 1

    7 Replies

    · Add your reply
    • Sort: 
    avatar image
    24
    Best Answer

    Answer by dmg0600 · Sep 24, 2014 at 01:44 PM

    You can do it with coroutines in any MonoBehaviour:

    1. IEnumerator ExecuteAfterTime(float time)
    2. {
    3. yield return new WaitForSeconds(time);
    4. // Code to execute after the delay
    5. }

    You can call it with, for example, StartCoroutine(ExecuteAfterTime(10));

    Note that it will execute asynchronous so put everything that has to wait for it to be done, inside the coroutine.

    Add comment · Hide 7 · Share
    avatar image Jan_Julius · Sep 24, 2014 at 01:46 PM 0
    Share

    But, when I call it from the update fuction befor the function before doing this will it not be called multiple times?

    avatar image Andres Fernandez · Sep 24, 2014 at 01:48 PM 0
    Share

    Call it somewhere else (like Start function). Check the tutorial.

    avatar image Jan_Julius · Sep 24, 2014 at 01:50 PM 0
    Share

    But what if it's done through there? how can I make it so it will only be executed once?

    avatar image Andres Fernandez · Sep 24, 2014 at 01:52 PM 0
    Share

    The start function only gets called once (at the beginning of the scene). Check the tutorial, try the code. It doesn't hurt.

    avatar image dmg0600 · Sep 24, 2014 at 01:55 PM 4
    Share

    If you call it in Update it will be executed once every frame, as if it were a normal method call or an invoke.

    If you want to be sure that it does not execute more than once until it finish its execution you can add a boolean flag:

     private bool isCoroutineExecuting = false;
     
     IEnumerator ExecuteAfterTime(float time)
     {
         if (isCoroutineExecuting)
             yield break;
     
         isCoroutineExecuting = true;
     
         yield return new WaitForSeconds(time);
      
         // Code to execute after the delay
     
         isCoroutineExecuting = false;
     }
    
    

    This way it will stop the new coroutine if it is still executing a previous one and start if it is not executing it yet.

    Show more comments
    avatar image
    33

    Answer by 767_2 · Sep 24, 2014 at 01:51 PM

    you can Invoke a method after a delay like this

    1. Invoke("DoSomething", 2);//this will happen after 2 seconds
    Add comment · Hide 5 · Share
    avatar image Jan_Julius · Sep 24, 2014 at 01:55 PM 0
    Share

    This freezes my Unity.

    avatar image 767_2 · Sep 24, 2014 at 02:02 PM 1
    Share

    if you put a function after invoke it will be executed immediately , why you say it freezes

    avatar image 767_2 · Sep 24, 2014 at 02:32 PM 0
    Share

    why you say it freezes

    avatar image Muskar · Mar 01, 2016 at 09:52 PM 4
    Share

    "DoSomething" is the name of the function to call. This answer is exactly what I needed, so I upvoted it, even though I know it wasn't the answer the OP was looking for.

    avatar image shaneparsons · Jul 14, 2016 at 01:31 PM 1
    Share

    Same as what @Muskar said – This isn't the answer the OP was looking for, but it's definitely what I was looking for!

    avatar image
    2

    Answer by UberGeoff · Feb 01, 2018 at 02:08 AM

    We can extend this futher by executing an Action after the delay:

    1. IEnumerator ExecuteAfterTime(float time, Action task)
    2. {
    3. if (isCoroutineExecuting)
    4. yield break;
    5. isCoroutineExecuting = true;
    6. yield return new WaitForSeconds(time);
    7. task();
    8. isCoroutineExecuting = false;
    9. }

    Then use it like this:

    1. StartCoroutine(ExecuteAfterTime(0.5f, () =>
    2. {
    3. //Add somwthing here
    4. }));
    Add comment · Hide 2 · Share
    avatar image KBVDev · Mar 29, 2018 at 10:09 AM 0
    Share

    What is the isCoroutineExecuting for? Im not sure if its doing anything

    avatar image Legend_Bacon KBVDev · Mar 29, 2018 at 10:23 AM 0
    Share

    It just makes sure the coroutine isn't already waiting for "time", and breaks if it is. Because most of the time, you don't want multiple instances of the same coroutine running in parallel.

    avatar image
    1

    Answer by HarshadK · Sep 24, 2014 at 01:45 PM

    Check Coroutines.

    It is exactly what you need.

    Add comment · Hide 1 · Share
    avatar image SaSha_K · Feb 06, 2017 at 03:11 PM 1
    Share

    Invoke() is simpler, but if one wants to call method with parameters, coroutine is apparently a good solution.

    avatar image
    1

    Answer by TomZe · Sep 26, 2018 at 03:47 PM

    use this class :

    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System.Reflection;
    4. using System.Linq;
    5. using UnityEngine;
    6. using System;
    7. namespace LateExe {
    8. class Executer
    9. {
    10. object script;
    11. MonoBehaviour mono_script;
    12. public Executer(object script)
    13. {
    14. this.script = script;
    15. this.mono_script = this.script as MonoBehaviour;
    16. }
    17. public InvokeId DelayExecute(float DelayInSeconds, Action<object[]> lambda, params object[] parameters)
    18. {
    19. return new InvokeId( mono_script.StartCoroutine(Delayed(DelayInSeconds, lambda, parameters)));
    20. }
    21. public InvokeId DelayExecute(float DelayInSeconds, string methodName, params object[] parameters)
    22. {
    23. foreach (MethodInfo method in script.GetType().GetMethods())
    24. {
    25. if (method.Name == methodName)
    26. return new InvokeId(mono_script.StartCoroutine(Delayed(DelayInSeconds, method, parameters)));
    27. }
    28. return null;
    29. }
    30. public InvokeId ConditionExecute(Func<bool> condition, string methodName, params object[] parameters)
    31. {
    32. foreach (MethodInfo method in script.GetType().GetMethods())
    33. {
    34. if (method.Name == methodName)
    35. return new InvokeId(mono_script.StartCoroutine(Delayed(condition, method, parameters)));
    36. }
    37. return null;
    38. }
    39. public InvokeId ConditionExecute(Func<bool> condition, Action<object[]> lambda, params object[] parameters)
    40. {
    41. return new InvokeId(mono_script.StartCoroutine(Delayed(condition, lambda, parameters)));
    42. }
    43. public void StopExecute(InvokeId id)
    44. {
    45. mono_script.StopCoroutine(id.coroutine);
    46. }
    47. IEnumerator Delayed(float DelayInSeconds, Action<object[]> lambda, params object[] parameters)
    48. {
    49. yield return new WaitForSeconds(DelayInSeconds);
    50. lambda.Invoke(parameters);
    51. }
    52. IEnumerator Delayed(float DelayInSeconds, MethodInfo method, params object[] parameters)
    53. {
    54. yield return new WaitForSeconds(DelayInSeconds);
    55. method.Invoke(script, parameters);
    56. }
    57. IEnumerator Delayed(Func<bool> condition, Action<object[]> lambda, params object[] parameters)
    58. {
    59. yield return new WaitUntil(condition);
    60. lambda.Invoke(parameters);
    61. }
    62. IEnumerator Delayed(Func<bool> condition, MethodInfo method, params object[] parameters)
    63. {
    64. yield return new WaitUntil(condition);
    65. method.Invoke(script, parameters);
    66. }
    67. }
    68. class InvokeId
    69. {
    70. public readonly Coroutine coroutine;
    71. public InvokeId(Coroutine coroutine)
    72. {
    73. this.coroutine = coroutine;
    74. }
    75. }
    76. }

    Examples: execute after 2 seconds in a few ways

    1. using LateExe;
    2. public class Game_Script: MonoBehaviour {
    3. void Awake {
    4. Executer exe = new Executer(this);
    5. exe.DelayExecute(2f , x=> Debug.Log("after 2 seconds"));
    6. exe.DelayExecute(2f , x=> Debug.log(x[0]) , "after 2 seconds + params");
    7. exe.DelayExecute(2f , "after2seconds");
    8. exe.DelayExecute(2f , "afterXseconds", 2);
    9. exe.DelayExecute(2f , "afterXY", 2, " seconds");
    10. }
    11. void after2seconds ()
    12. {
    13. Debug.Log("after 2 seconds");
    14. }
    15. void afterXseconds(int x) {
    16. Debug.log("after" + x + "seconds");
    17. }
    18. void afterXY(int x , string y) {
    19. Debug.log("after " + x + y);
    20. }
    21. }

    Example stop:

    1. var id = exe.DelayExecute(0.5f, x => Debug.Log("not gonna run"));
    2. exe.StopExecute(id);

    Example when:

    1. exe.ConditionExecute(() => score > 100 , x => Debug.Log("you're good"));

    I know this is old but its a very common thing and I hope unity will one day implement such a class into the engine. creating a coroutine every time is not a clean way of doing things.

    Add comment · Share
    • 1
    • 2
    • ›

    Your answer

    Hint: You can notify a user about this post by typing @username

    Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

    Welcome to Unity Answers

    The best place to ask and answer questions about development with Unity.

    To help users navigate the site we have posted a site navigation guide.

    If you are a new user to Unity Answers, check out our FAQ for more information.

    Make sure to check out our Knowledge Base for commonly asked Unity questions.

    If you are a moderator, see our Moderator Guidelines page.

    We are making improvements to UA, see the list of changes.



    Follow this Question

    Answers Answers and Comments

    41 People are following this question.

    avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

    Related Questions

    weapon bobbing 1 Answer

    How to make an enemy respawn? 0 Answers

    Autodetect new assets on Mac takes a minute 0 Answers

    Portal Sound start AFTER the Teleportation 0 Answers

    On Trigger Enter no longer works? long delay to activate 2 Answers