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 ronronmx · Jan 27, 2011 at 06:16 AM · coroutinewhile-loop

Confused about while loops in C#

so I'm rather new to while loops with C#...I have the following code:

if (boostCharge > 0 && !bikeEngine.boostIsOn) {
   boostCharge--;
}
/*      
while (boostCharge > 0 && !bikeEngine.boostIsOn) 
{
   boostCharge--;
}
*/

using "if", the boostCharge variable slowly goes down on every frame. But using "while", boostCharge goes straight to 0, why is that? Do while loop have to be in a Coroutine in C#?

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 zharramadar · Jan 28, 2011 at 04:00 PM

You are seeing the if method in the wrong angle.

For a moment, forget about your Update funcion, lets assume a generic function.

If is only a comparison function, in other words, it will just evaluate if the condition between parenthesis is true, and if so, will execute the code between brackets. If is not a loop function.

While, in the other hand, is a loop function. It will execute while the condition between the parenthesis is true, and will only exit its loop when the condition becomes false.

The impression you have that IF is actually doing a per-frame loop is solely because Update is being called every frame, and thus, it will evaluate your condition in the IF once per frame. If is not being responsible for the loop, but your update function is.

With the while, every frame Update is called, and within Update, it'll loop internally until your condition in the WHILE is false, and in your example, this happens when boostcharge <= 0. So, every frame, you start boostcharge with, lets say, 10, and it'll exit with 0. In other words, you have a loop (the WHILE command) within another "loop" (the Update function).

The if method works because your boostcharge variable probably is class-scoped, so it'll persist the value of the variable between Update calls.

The FOR command will work exactly as WHILE, giving that your condition is met in the for loop as well.

Hope you now understand the difference between your IF and your WHILE inside the Update method.

Comment
Add comment · Show 2 · 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 Bunny83 · Jan 28, 2011 at 04:12 PM 0
Share

Well explained. Can't add anything else. If that explaination isn't enough i would recommend a program$$anonymous$$g / scripting lesson to learn the very basics. Because that's how nearly every program$$anonymous$$g / scripting language works.

avatar image ronronmx · Jan 29, 2011 at 05:46 PM 0
Share

Yes indeed, well explained. It makes a lot more sense now so thank you for your time, I really appreciate it!

avatar image
1

Answer by Bunny83 · Jan 27, 2011 at 06:42 AM

Like all code within a function even loops are executed immediately. Your Update() function is called every frame by Unity, but the code inside is executed "as fast as possible". A while loop is a loop inside your function it will run until the condition is false. So in your example if boostCharge is 10 and your code is executed, right after the while block boostCharge will be 0, because the while won't exit until boostChange is <= 0.

That's why you have to be carefully with loops, you can make a loop that runs forever and will block everything (in layman's terms it's called: crash)

You can try this (but be careful if executed within Unity the whole editor will crash):

// !!!! // USE AT YOUR OWN RISK ! // !!!!

void Update() { while(true) { } }

As I said: be careful and save everything before you test something like that.


Some further information:

Unity is a program. It offers you the possibillity to extend it's function. In Unity you can create a GameObject and add a components to it. A special component is the MonoBehaviour component. MonoBehaviour is a class that offers Unity some functions. Such a class is also called interface. Because the class have some explicit functions that are known to unity so unity is able to use them. When you write you own script it's "based" (or to be correct derived from) MonoBehavior.

A program is like a single function. In a lot of programming languages (like c++, java, c#,...) it is actual a function that is named "main()". This function is called by your operating system when you start your program. When you leave this function the program is done and exits. To keep your program running you have to make a loop. Since you're not alone on this PC you have to call some operating system functions that handles the mouse and keyboard input.

In case of Unity the actual program is hidden from you. The Unityplayer (web or standalone...) is also just a program with a main function. Inside this function unity handles the input and also processes the GameObjects you've created.

// That's just a simplified pseudo main function

bool IamStillRunning = true;
void main()
{
   while(IamStillRunning)
   {
      CallSomeOSFunctions();
      foreach(GameObject O in scene)
      {
         O.Update();
      }
      // when all GameObject updates are finished call LateUpdate();
      foreach(GameObject O in scene)
      {
         O.LateUpdate();
      }
      // There will much more like, rendering, physics calculations, ...
   }
}

Now look at this, if only one of your Update function doesn't return the whole program will stuck inside your Update function. I don't want to give a whole lesson in application developing but maybe this helps a bit to understand what's happening "under the hood".

Comment
Add comment · Show 3 · 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 ronronmx · Jan 28, 2011 at 06:33 AM 0
Share

How come "while" loops crash the editor? It happened to me many times and took me a while to figure out why it was crashing...lol

avatar image Bunny83 · Jan 28, 2011 at 04:20 PM 0
Share

Your code is executed inside the editor if you press the play button. The editor application is build on top of the Unity engine. When your game runs the engine (unity) will call your function Update() and gives you the control. You are a part of this application at that moment. When you finished your Update function it returns the control back to unity. But if you stay inside your Update function unity (and the editor) will freeze until you exit your function.

avatar image ronronmx · Jan 29, 2011 at 05:48 PM 0
Share

Thanks a lot for the explanation, it helps a lot and it's all starting to make sense now.

avatar image
0

Answer by DaveA · Jan 27, 2011 at 07:06 AM

Assuming that 'if' is in an Update, that statement will execute once per frame. The while statement will execute IN ONE FRAME.

What are you trying to achieve? Because even once per frame is pretty fast.

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 ronronmx · Jan 28, 2011 at 06:32 AM 0
Share

Yes both if and while are in Update. How come a "while" loop executes in one frame and not once per frame like an "if" or "for" loop?

Thanks!

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

No one has followed this question yet.

Related Questions

While loop out of control...maybe? I'm not sure. Trying to track Coroutines progress. 1 Answer

fps calculation with while loop in coroutine 2 Answers

Coroutine WHILE function not finding GO 0 Answers

Android coroutine loop ruins game 1 Answer

Coroutine not waiting for While Loop to finish 1 Answer


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