- Home /
I broke my game with what i think is an infinite loop?
I'm new to Unity, and I was working on a script to control a fire. When the player is close, and the fire is off, player can light the fire by pressing f, when the fire is on, player can turn it off by pressing f. However, when I run the script, the game freezes and i have to restart my laptop to unfreeze it. Can someone explain what I did wrong and how to fix it?
Answer by ScareCrow95 · Jul 25, 2018 at 08:44 PM
There are quite a few things wrong with your code. Can you explain why are you running a for loop upto 100?
And it is an infinite loop, and "GetKey" means it will return true every frame while the key is pressed. You should be using "Getkeydown".
try something like this:(there will be syntax errors, I typed on my phone)
bool canControlFire;
onTriggerEnter - canControlFire=true; (you can turn on the text hint here)
ontriggerExit - canControlFire = false;(you can turn off the text hint here)
void Update(){
if(canControlFire)
{
if(Input.GetKeyDown("f"))
{
if(fire.isActiveInHiearchy) // is fire active?
fire.setactive(false);
else
fire.setactive(true);
}
}
}
Thanks. I ran the for loop up to 100 because I wasnt sure how to keep the program checking for a key input. But now, as Bystander33 pointed out, I know I could just use the update() function.
Answer by Bystander333 · Jul 25, 2018 at 09:01 PM
First of all, use GetKeyDown or GetKeyUp instead of GetKey which returns true the entire time the key is pressed. Secondly don't us Coroutines for this - just do it all in Update(). In OnTriggerEnter set a boolean called e.g. playerIsNear to true and set it to false in OnTriggerExit. The in Update,
if ((playerIsNear) && (GetKeyUp(KeyCode.F))
{
fireislit = !fireislit;
fire.SetActive(fireislit);
}