Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
-1
Question by Nebula X · Feb 10, 2016 at 11:49 AM · animationbooleanif-statements

How do I make a gun reload after 30 shots?

Ok, Im currently making a FPS game which involves animations with reloading, firing, and drawing a weapon. I need to make it so that my weapon stops and reloads after shooting 30 bullets. I also want the weapon to stop shooting after all of the clips run out (total of 3). I need help on making this. The script I'm using is below.

 var drawAnim : String = "Draw";
 var fireLeftAnim : String = "Fire";
 var reloadAnim : String = "Reload";
 var animationGO : GameObject;
 
 
 private var drawWeapon : boolean = false;
 private var reloading : boolean = false;
  
 function Start (){
 DrawWeapon();
 }
  
 function Update (){
  
     if(Input.GetButton ("Fire1") && reloading == false && drawWeapon == false){
         Fire();
         }
        
         if (Input.GetKeyDown ("r") && reloading == false && drawWeapon == false){
     Reloading();
         }
        
         if (Input.GetKeyDown ("1") && reloading == false){
         DrawWeapon();
         } 
     
 
 }
  
 function Fire(){
     animationGO.GetComponent.<Animation>().CrossFadeQueued(fireLeftAnim, 0.08, QueueMode.PlayNow);
 }
  
 function DrawWeapon() {
   if(drawWeapon)
     return;
        
         animationGO.GetComponent.<Animation>().Play(drawAnim);
         drawWeapon = true;
         yield WaitForSeconds(0.6);
         drawWeapon = false;
        
 }
  
 function Reloading(){
      if(reloading) return;
    
         animationGO.GetComponent.<Animation>().Play(reloadAnim);
         reloading = true;
         yield WaitForSeconds(2.0);
         reloading = false;
 }


Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image davidallyson159 · Apr 12, 2018 at 08:30 PM 0
Share

It worked here !

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class Gun$$anonymous$$anager : $$anonymous$$onoBehaviour {

 [Header("Tiro")]
 //Lançamento das balas//
 public Rigidbody Projetil;
 public Transform SpawnBullet;
 public float VelocidadeDaBala = 20;
 //Lançamento das balas//

 [Header("$$anonymous$$ira")]
 //$$anonymous$$ira//
 public Transform GunPrefab;
 public GameObject miraCanvas;
 public Vector3 Aim;
 public Vector3 Hip;
 //$$anonymous$$ira//

 //Reload//
 [Header("Reload")]
 public float TempoDeReload;
 public int BalasNoPente = 30;
 int balastart;
 public int BalasForaDoPente = 90;
 int bulletfor;
 bool reload;
 //Reload//
 void Start () {
     BalasForaDoPente = 90;
     bulletfor = 0;
     balastart = BalasNoPente;
 }
 void Update () {
     //========Lançador_SE$$anonymous$$I_AUTO$$anonymous$$ATICO========//
     if (BalasNoPente > 0) {
         if (Input.GetButtonDown ("Fire1")) {
             BalasNoPente --;
             bulletfor++;
             Rigidbody instantiateProjetil = Instantiate (Projetil, SpawnBullet.position, SpawnBullet.rotation) as Rigidbody;
             instantiateProjetil.velocity = transform.TransformDirection (new Vector3 (0, 0, VelocidadeDaBala));
         }
     }
     //========Lançador========//


     //========$$anonymous$$ira========//
     if (Input.Get$$anonymous$$ouseButton (1)) {
         GunPrefab.localPosition = Aim;
         miraCanvas.SetActive (false);
     }
     if (Input.Get$$anonymous$$ouseButtonUp (1)) {
         GunPrefab.localPosition = Hip;
         miraCanvas.SetActive (true);
     }

     //=====Reload======//
     if (BalasNoPente < balastart) {
         reload = true;
     } else {
         reload = false;
     }
     if (Input.Get$$anonymous$$eyDown ($$anonymous$$eyCode.R) && reload == true) {
         StartCoroutine(Reload());
     }
 }
     IEnumerator Reload(){
     yield return new WaitForSeconds (TempoDeReload);
     BalasNoPente += bulletfor;
         BalasForaDoPente -= bulletfor;
     bulletfor = 0;
     }
             //=====Reload======//

}

4 Replies

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by ItsIcear · Feb 10, 2016 at 05:39 PM

First, create an int that keeps track of your current ammo count and a bool

 var ammoCount : int = 30;      // Use Whatever Value You Like
 var emptyMagazine : bool = false;

Then when you call the "Fire" function, decrement the "ammoCount" value by 1

    ammoCount--;

In your Update function or in your fire function, add the lines

 if(ammoCount <= 0)
 {
     Debug.Log("No ammo left in magazine");
     emptyMagazine = true;
 }
 
 if(Input.GetKeyDown(KeyCode.R) && emptyMagazine)
 {
     Reload();
 }

Also change you Fire calling to

 if(Input.GetButton ("Fire1") && !reloading && !drawWeapon && !emptyMagazine)
 {
       Fire();
 }
 
 // The "!drawWeapon" function does the same as "drawWeapon == false"

Then in your Reload function

 ammoCount = 30;    // Or Whatever Value You Selected Up Top
 emptyMagazine = false;

This should count the number of bullets you have left in the magazine, which could be useful when making a HUD. Also the gun will not fire if you have no bullets left in the magazine. Hope this helps and good luck with you game!

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Nebula X · Feb 12, 2016 at 06:43 PM 0
Share

I just finished creating a shoot script that will clone a bullet and launch it using instantiate and ray cast. How do I add the shoot script to my weapon script (the one earlier) so that the bullets would stop cloning and shooting after the 30 shots run out? Ive tried it before but something went wrong. (script below)

 #pragma strict
 
 var bulletTex : GameObject[]; 
 var power : int = 10; 
 function Start () 
 {
  
 }
  
 function Update () 
  {
  
 var fwd = transform.TransformDirection(Vector3.forward); 
 var hit : RaycastHit;
  
 Debug.DrawRay(transform.position, fwd * 10, Color.green); 
 if(Input.GetButtonDown ("Fire1") && Physics.Raycast(transform.position, fwd, hit, 10)){ 
 Instantiate(bulletTex[Random.Range(0,3)], hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal)); 
 
  
 if (hit.rigidbody !=null)
  
 hit.rigidbody.AddForceAtPosition(fwd * power, hit.point);  
 }
  
 }
 

avatar image ItsIcear Nebula X · Feb 19, 2016 at 08:03 PM 0
Share

When instantiating the bullet prefab, use the "Destroy" function, like this...

 var timeUntilDestroy : float = 5f;
 
 Destroy((prefab), timeUntilDestroy);
avatar image
1

Answer by rajan4uto · Feb 10, 2016 at 11:58 AM

in your fire method put a counter and check every time whether it reach 30 or not. For Example:

 function Fire()
 {
            count--;
 if(count==0)
 {
           //reload your gun(use your own method here)
           count=30;
 }
 }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by RealSoftGames · Feb 10, 2016 at 12:08 PM

ok so we need to modify your code a fair bit here, you dont have anything that controls ammo, so lets add this

int ammo = 30, stock ammo = 90; // ammo is what will be in your gun and stock ammo will be the stock pile you have in terms of clips etc.

in your fire method

in

  function Fire(){
 if(ammo > 0){
      animationGO.GetComponent.<Animation>().CrossFadeQueued(fireLeftAnim, 0.08, QueueMode.PlayNow);
 
 //add
 ammo--;  //this will control the ammo in the gun making it reduce everytime you fire
 }
 else
 //reload here if your ammo is not greater than 0
  }



Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Nebula X · Feb 12, 2016 at 04:48 PM

Ok thanks!

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Help with bools and if else statements. Animations 2 Answers

Bool changes back instantly 3 Answers

Selecting animation to play based on boolean 1 Answer

Play animation on mouse click 1 Answer

Play animation when WASD is pressed, stop animation when none of them are pressed (Help!!) 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges