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. Dismiss Notice

Count how many times a function has been called? To activate a reload.

Discussion in 'Scripting' started by MarteenGreen, Dec 14, 2014.

  1. MarteenGreen

    MarteenGreen

    Joined:
    Dec 14, 2014
    Posts:
    4
    I have a script called PlayerShooting.cs, and in there is a function called void Shoot().

    Shoot() gets called in the Update() function on that script whenever the player presses the left mouse button.

    My question is, how do I count the number of times they shot, so I can use a Reload function after a certain amount of shots?

    Thanks
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    You do it with an int variable that is outside the function.
     
  3. kelvinwop

    kelvinwop

    Joined:
    Dec 15, 2014
    Posts:
    36
    Code (CSharp):
    1. int ammo = 20;
    2. //your function here
    3. //implementation not shown
    4.     ammo--;
    5.  
    6. //reload function
    7. if(ammo <!=20)
    8.     ammo=20;
    9.  
    not sure how to use a function in CS, so its a bit ghetto.
     
    huseynhesen889 likes this.
  4. MarteenGreen

    MarteenGreen

    Joined:
    Dec 14, 2014
    Posts:
    4
    Ah, I see. Way easier than I thought haha. Thanks, guys!
     
    huseynhesen889 likes this.
  5. MarteenGreen

    MarteenGreen

    Joined:
    Dec 14, 2014
    Posts:
    4
    Follow up question, the player can reload their weapon now (yay!), but when they press the 'R' button, it snaps from 0 bullets to 50 instantly.
    How can I add a wait time right as they push the "r" button, and then fill their bullets back up?

    Code (CSharp):
    1.  
    2. //WAITTIME - how?!?!!?!?!
    3. if (Input.GetKeyDown("r"))
    4.  {
    5.        AmmoCounter.ammo = 50;
    6.  }
    7.  
     
  6. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    In c#, you have to write a coroutine. It's probably best to look it up in the unity script reference.
     
  7. kelvinwop

    kelvinwop

    Joined:
    Dec 15, 2014
    Posts:
    36
    add a counter and increment the counter in the
    void FixedUpdate()

    ps. FixedUpdate is called every 0.02 seconds, or 50 times a second.
     
  8. huseynhesen889

    huseynhesen889

    Joined:
    Mar 9, 2021
    Posts:
    1
    thank you for writing I needed that function