Search Unity

Unity Crashing when running script

Discussion in 'Scripting' started by sunstone124, Nov 20, 2014.

  1. sunstone124

    sunstone124

    Joined:
    Dec 11, 2012
    Posts:
    5
    I have a script to make a flashlight run out of battery and it says I have no errors in the script. When I press the run button to test the game it crashes. I know it is this becuase when I remove this script it does not crash any more. Does anyone know what I should do to fix this?
    Script:
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var flashLight_battery = 100;
    4. var flashLight_powered = true;
    5. var flashLight_drain = 0.1;
    6.  
    7. function Update() {
    8. if(flashLight_battery < 0){
    9. flashLight_Powered = false;
    10. }
    11. while(flashLight_Powered){
    12.  
    13. if(Input.GetButtonDown("Fire1")){
    14.      light.enabled = !light.enabled;
    15. }
    16.  
    17. if((!flashLight_Powered)){
    18. light.enabled = false;
    19. }
    20.  
    21. if(light.enabled){
    22. flashLight_battery = flashLight_battery - flashLight_Drain;
    23. }
    24.  
    25. }
    26. }
     
  2. smd863

    smd863

    Joined:
    Jan 26, 2014
    Posts:
    292
    You have an infinite loop. If "flashLight_Powered" is true, you will loop forever. You don't need a "while" loop because Unity will automatically call the Update() function every frame. You also need to re-arrange some of your logic a bit.

    Something like this:

    Code (JavaScript):
    1.  
    2.  
    3. function Update() {
    4.  
    5. // Update flash light state
    6. if(flashLight_battery > 0){ // If we have battery power
    7.      if(Input.GetButtonDown("Fire1")){ // Allow the player to toggle the power
    8.           flashLight_Powered = !flashLight_Powered;
    9.      }
    10. }
    11. else { // Else flash light is always unpowered
    12.      flashLight_Powered = false;
    13. }
    14.  
    15. // Update the light and battery based on the updated flashlight state
    16. if (flashLight_Powered){ // If powered, activate light and drain battery
    17.      light.enabled = true;
    18.      flashLight_battery -= flashLight_Drain;
    19. }
    20. else{ // Else disable the light
    21.      light.enabled = false;
    22. }
    23.  
    24. }
    25. }
    Edit: You should also move this to FixedUpdate() or take into account the delta for each frame. With this code your flashlight will drain much faster on a very fast computer.
     
    image28 likes this.
  3. sunstone124

    sunstone124

    Joined:
    Dec 11, 2012
    Posts:
    5
    Thank you very much, I just had to change a few things to better suit my needs in the context, other wise it was great!