Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

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

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Redmoth · Mar 27, 2013 at 07:45 PM · c#waitforsecondswait

Csharp: how to make script wait for x seconds

Hi everybody!

currently, to wait in scripts, i make a float variable that augments every frame, and when it reaches a threshhold, the script continues on. so if the frames per second of the game is 30:

public float WaitTime = 0.0f; public float Threshhold = 90f;

WaitTime++;

The WaitTime will be of 3 seconds before it reaches the threshhold. I am sure this has a huge hit on performance if you have hundreds of scripts using this technique.

I researched on the IEnumerator and YieldForSeconds thing, but cannot seem to comprehend it. Is there any simple way to wait an amount of time in Cscripts or can somone explain in detail IEenumerator and YieldForSecond functions for a noob? thank you very much :)

if anyone is still unsure of what I am asking, I want to know how to make my script wait a number of seconds before passing to the next line of code. Thanks!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

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

Answer by iwaldrop · Mar 27, 2013 at 07:56 PM

Coroutines and Invokes are very simple to use, actually. I suggest you spend some time acquainting yourself with them. All of your projects will benefit from their use.

For instance, if you wanted something to repeat every 3 seconds you could use either a Coroutine or an Invoke.

 using UnityEngine;
 using System.Collections;
 
 public class Test : MonoBehaviour
 {
     public bool useInvoke;
     public bool running;
     
     void Start()
     {
         if (useInvoke)
             InvokeRepeating("TestInvoke", 0, 3);
         else
             StartCoroutine(TestCoroutine());
     }
     
     void TestInvoke()
     {
         Debug.Log("TestInvoke()");
     }
     
     IEnumerator TestCoroutine()
     {
         running = true;
         
         while (running)
         {
             Debug.Log("TestCoroutine()");
             yield return new WaitForSeconds(3);
         }
     }
 }
 

Attach that script to a gameObject and play with the useInvoke flag from the inspector if you want. Unchecking the running box in the inspector will quit the coroutine. Hopefully you can use this as a template to implement your own! Good luck!

Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Redmoth · Mar 27, 2013 at 09:33 PM 0
Share

Thanks, but suppose does this work for:

suppose i have a script wich does:

somevar = 1; "Wait 3 seconds"; somevar = 3

somevar will be 1, then after 3 seconds change to 3.

How would i go about achieving this? calling the functions you mentionned above in the script? a bit like:

somevar = 1; test.testinvoke(); somevar = 3;

or

somevar = 1; test.TestCoroutine(); somevar = 3;

?

thanks for quick answer!

avatar image iwaldrop · Mar 27, 2013 at 09:43 PM 1
Share

Yes. If you want to wait to set a variable then you simply set it after the delay.

 private int valueToSetTo;
 
 void Start()
 {
     valueToSetTo = 5;
     Invoke("SetVariable", 3);
 }
 
 void SetVariable()
 {
     someVar = valueToSetTo;
 }
avatar image iwaldrop · Mar 27, 2013 at 09:43 PM 0
Share

And please mark this question as answered. I'll still help you along, but we might as well get it off of the unanswered list. :)

avatar image Redmoth · Mar 27, 2013 at 10:18 PM 0
Share

Thank you very much :)! I like that Invoke trick. Very usefull and simple indeed, I didn't even know such a function existed! That should do the trick, thanks for the answer!

avatar image
1

Answer by Deniz2014 · Mar 22, 2017 at 10:49 PM

I wanted to wait x Seconds in the Update() before continuing. So you cannot use the yield there (don't want to start a coroutine every frame right?)

So if someone, like me, searched this / needs this in and for the Update():

 private float timer = 0;
 
 private float timerMax = 0;
 
 void Update ()
 {
    text += "Allow yourself to see what you don’t allow yourself to see.";
 
    if(!Waited(3)) return;
 
    text += "\n\nPress any key!";
 }
 
 
 private bool Waited(float seconds)
 {
     timerMax = seconds;
 
     timer += Time.deltaTime;
 
     if (timer >= timerMax)
     {
         return true; //max reached - waited x - seconds
     }
 
     return false;
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Estevominador · Apr 11, 2013 at 05:55 PM

what about when the code is not in a void? for example:

GameObject muzzleflash = instantiate...

yield WaitForSeconds (0.4f); Destroy (muzzleflash);

this code above don't work. how could I do lines of code that simple without create a new void?

I tried to use IEnumerator like this;

GameObject muzzleflash = instantiate...

Wait (0.4f); Destroy (muzzleflash);

IEnumerator Wait (float amount) { yield return new WaitForSeconds (amount); }

please tell me what I am doing wrong.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image iwaldrop · Apr 11, 2013 at 06:06 PM 0
Share

This is not an answer, it's a question. To answer it, however, you cannot have a yield statement outside of an IEnumerator in C#.

Also, for what you seem to be doing, you don't want to create and destroy the muzzleflash, you just want to activate and deactivate it's renderer and any pertinent effects (like lighting, et al).

 bool flashIsActive = false;
 bool isFiring;
 
 void Set$$anonymous$$uzzleFlashActive(bool setActive)
 {
     muzzleflash.renderer.enabled = setActive;
 }
 
 void Fire()
 {
     StartCoroutine(FireEffects(0.4f));
 }
 
 IEnumerator FireEffects(float waitTime)
 {
     do
     {
         Set$$anonymous$$uzzleFlashActive(!flashIsActive);
         yield return new WaitForSeconds(waitTime);
     }
     while (isFiring);
     flashIsActive = isFiring;
     Set$$anonymous$$uzzleFlashActive(flashIsActive);
 }

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.

Follow this Question

Answers Answers and Comments

13 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

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Does Scripting Jump exist? (How To use/write goto) 3 Answers

AssetBundles coding 1 Answer

Waiting then Executing 4 Answers

C# wait X-Seconds in Code before continue in Code? 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges