- Home /
Power charger script problem
I have a problem with my script, so I would appreciate if someone could help me.
It is a power charger. It should go automatic from 1 to 200, and thend go back from 200 to 1. Here's the code:
var att1 : int = 10;
function Update() {
do {att1+=Time.time;}
while(att1<=200);
if(att1==200){
do {att1-=Time.time;}
while(att1>=0);}
}
function OnGUI () {
GUI.Box(Rect(155,202.8,att1*2,15),"");
}
Every time I run it, it goes from 1 do 200 and then whole Unity freezes
This happens because the Update runs once per frame- it is already managing the looping behaviour for you! If you have a while loop using something which doesn't change until the end of the frame (for example, Time.time, or Input.GetButton("Whatever")), then it will always freeze up.
Answer by BerggreenDK · Nov 02, 2011 at 12:19 PM
first declare your custom state for this pattern/statemachine
public enum PowerState
{
PowerUp,
PowerDown
// easily add more states if you need them here
}
PowerState chargerState = PowerState.PowerUp;
in your update or where you need to check it, use a SWITCH instead of IF. Because its easier to maintain and build out with multiple states
switch (chargerState)
{
case PowerState.PowerUp:
att1 += Time.deltaTime;
if (att1 >=200) chargerState = PowerState.PowerDown;
break;
case PowerState.PowerDown:
att1 -= Time.deltaTime;
if (att1 <0) chargerState = PowerState.PowerUp;
break;
// add more states if you want more interesting patterns
default: // if no other conditions are true
Debug.Log("unknown state: " + chargerState);
break; // always remember to end with a break pr. case, also default case
}
I decided to mark your question as correct answer ,because I decided to put up one more state, when you press certain key that charger stops and saves current value.
cool! thanks. I just wanted to show you another approach than using IF...THEN, because state-machines are so much more fun to scale up.
Answer by Anxo · Nov 02, 2011 at 05:21 AM
That is because you are getting stuck in a while loop. You dont need "while" in this case.
Poweringup : boolean = true;
if(att1 <=0)
{
Poweringup = true;
}
if(Poweringup)
{
att1+=1*Time.deltaTime;
}
if (att1 >=200)
{
Poweringup = false;
}
if(!Poweringup)
{
att1-=1*Time.deltaTime;
}
Thanks...Is there any way to do this without boolean.Just curious
Your answer

Follow this Question
Related Questions
Sound script problem. 0 Answers
problem with my simple script please help. 2 Answers
Car wheel problems 1 Answer
problem with raycasts and tags 1 Answer