these codes are hanging unity.

When i’m using these codes,

void OnGUI()
{
While(input.key(“p”))
{
Shoot =1;
Power+=5;
If(power>40)
{Power=40;
Break;}
}
}

These codes are giving no errors. But if i press p during run time. Unity hangs and i have to force close it…

So what should i do ?

Dont use a while loop, use an ‘if’ statement.

… I think its best if you just learn the new system, lots wrong with that code

Why are you using While Loops? I think this can easily be done by using an IF statement. But while loop shouldn’t be a problem anyways. Try to put this script on another object and see if it’s working fine or not. Maybe another project.
Also use the code tags from next time. Makes code easier to read. In text editor , INSERT > CODE.

Well,I want to know ,what is wrong with this code .

If statement is working, but not the way i want. I can’t use the “break” part in if statement.
I want ,when user press p, the power increase and when he release the key the loop ends (simple)…
The question is , is it turning into an infinite loop ,or something like that ?

1 Like

I’m surprised this code compiles at all.

You can try it.:sunglasses::smile:

A SWITCH statement can do exactly the same thing. It has a break function.
But trust me you can do that with an IF statement too , like that :

public bool loopEnd;

public int p;

void Update()
{
  if(Input.GetKey(Keycode.Space)
   {
      loopEnd = false;
       p++;
    }
   else
     {
       loopEnd = true;
      
      
      }

     If(loopEnd == true)
        {
           print(p);
         }
}
1 Like

Input.GetKey returns true on every frame that key is down.

One frame is the time it takes for all of the Update functions to run.

Your while-loop will keep running until the key isn’t registered as down anymore, and prevent the Update from finishing. Since your Update needs to finish before the key is registered as down, the while-loop will never exit.

3 Likes

True that!

also impressed it does anything - you’re using capital V on void to start your function there… keep an eye out for that.

“void start” is a lot worse, as it compiles and does nothing. I’m pretty sure OP’s code isn’t copy-pasted, though.

hey, @willgoldstone , maybe a console warning about Unity-Methods written with lowercase letters could be implemented? I’ve probably answered half a million questions on UA and here where the solution was “put a big U on Update”.

2 Likes

I didn’t copy paste it.:face_with_spiral_eyes::rage:
I wrote this code on my phone.

1 Like

I think I’ll just lock this thread. Come back when serious :slight_smile:

2 Likes