Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How i can solve this problem? js

Discussion in 'Scripting' started by masterjohn12, Sep 29, 2015.

  1. masterjohn12

    masterjohn12

    Joined:
    Nov 26, 2013
    Posts:
    2
  2. MrPriest

    MrPriest

    Joined:
    Mar 17, 2014
    Posts:
    202
    Well, you basically say if you have extraAmmo <=0, you can't reload.
    BUT later you ask "if currentClip < 5", you CAN reload.
    You should work on your switches.
    I think this should do the work. I did not change it too much.
    Try and see if there are any other ways to make it clearer and minimize code re-use.

    Code (JavaScript):
    1. function booleans()
    2. {
    3.     if(extraAmmo <= 0)
    4.     {
    5.         extraAmmo = 0;
    6.         canReload = false;
    7.     }
    8.     else if(currentClip < 5)
    9.     {
    10.         canReload = true;
    11.     }
    12.  
    13.     if(currentClip <= 0)
    14.     {
    15.         canShoot = false;
    16.     }
    17.     else
    18.     {
    19.         canShoot = true;
    20.     }
    21.              
    22.     if(canShoot == true)
    23.     {
    24.         shootUp();
    25.     }
    26. }
     
  3. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,199
    I think it's much cleaner to caclulate the bools directly:

    Code (JavaScript):
    1. if(extraAmmo < 0)
    2.     extraAmmo = 0;
    3.  
    4. canReload = extraAmmo > 0 && currentClip < 5;
    5.  
    6. canShoot = currentClip > 0;
    7.  
    8. if(canShoot)
    9.     shootUp();
     
    Kiwasi likes this.
  4. MrPriest

    MrPriest

    Joined:
    Mar 17, 2014
    Posts:
    202
    I agree, but I wanted to fix his code, not rewrite it.
    I like reaching conclusions by myself, otherwise they don't stick in.
    I figure it's the best way to help.
     
  5. masterjohn12

    masterjohn12

    Joined:
    Nov 26, 2013
    Posts:
    2
    Thanks for every1, but I have 1 bullet in my extraAmmo with 1 bullet in my currentClip, for example. Still I can reload and receive 4 bullets, even with 1 extraAmmo
     
  6. MrPriest

    MrPriest

    Joined:
    Mar 17, 2014
    Posts:
    202
    Code (JavaScript):
    1. if(canReload == true){
    2. if(Input.GetKeyDown(KeyCode.R)){
    3.         difference = extraAmmo  - currentClip;
    4.         currentClip += difference;
    5.      
    6.         extraAmmo -= difference;
    7. }
    You have always used "5" when calculating the difference, instead of the ammo you currently have (the above code is fixed).