Firing a Gun

Well, needless to say If I’m posting here what I wrote didn’t work. Although since I’m a newbie it doesn’t surprised me. Basically what I was writing was a Gun script. If you pressed the Left Mouse it would shoot when you released and then minus out one bullet. If your bullets were less than the maximum 8 you could reload by pressing R. Here’s the Code:

using UnityEngine;

using System.Collections;

public class PistolShoot : MonoBehaviour {
	public float MaxAmmo;
	public float CurAmmo;

}
	// Use this for initialization

	void Start () {
	MaxAmmo = 8;
	CurAmmo = 8;	
	}

	// Update is called once per frame

	void Update () {
	//Firing...
	if(Input.GetMouseButtonUp(LeftMouse))
			if(CurAmmo > 0) {
			Instantiate(Bullet, SpawnBullet, Quaternion.SpawnBullet);
			CurAmmo = CurAmmo - 1;
		}
	//Reloading...
	if(Input.GetKeyUp(KeyCode.R));
	   if(CurAmmo < MaxAmmo);
	   CurAmmo = MaxAmmo ;
	}

Any help would be great.

“didnt work”
…what didnt work?
…what errors did you get?
…what is the expected behavior?
…what is the current behavior?

Being a new developer - when you post for help PLEASE be as descriptive as possible - or else you wont get an answer.

Anyhow:

IMPORTANT: Make sure your BULLET prefab has a rigidbody attached:
Select Bullet in the Inspector
Component Menu > Physics > Rigidbody

objects with rigidbodys have physics applied to them by nvidia physx (i believe thats the unity physics engine)
this allows us to use the AddForce method on the bullet to push it forward

using UnityEngine;
using System.Collections;

public class SimpleGun : MonoBehaviour {
	//these really should be private, however, im leaving them as public
	//for assignment in the inspector
	public int clipSize=8;
	private int ammoInCurrentClip; //ammo in our current clip
	
	private float bulletSpeed=100000f;//speed the bullet travels at
	
	public GameObject bulletPrefab; //assign this variable from the inspector
	private Transform firingPoint;
	
	// Use this for initialization
	void Start () {
		ammoInCurrentClip=clipSize;
		
		//get a reference to our firing point
		firingPoint=transform.Find ("FiringPoint"); //find the child FiringPoint of the gameobject this script is attached to (a gun)
	}
	
	// Update is called once per frame
	void Update () {
		//if the user has left clicked
		if (Input.GetMouseButtonDown (0)){
			
			//if we have ammo in the current clip, fire
			if (ammoInCurrentClip>0){
				//Instantiate our bullet prefab at the position and rotation of the firingpoint
				GameObject bullet=(GameObject)GameObject.Instantiate(bulletPrefab,firingPoint.position,firingPoint.rotation) as GameObject;
				
				//add force in the transform.forward direction (this is a normalized vector pointing in the direction the gun is facing)
				//The forward vector is the BLUE arrow in your scene preview
				//Example if the blue arrow was facing in the positive X direction this would be (1,0,0) 
				//You can use Debug.Log (transform.forward); if you want to see these values
				bullet.rigidbody.AddForce (transform.forward*(bulletSpeed*Time.deltaTime));
				
				// currentAmmo-- is a shortcut for currentAmmo=currentAmmo-1
				ammoInCurrentClip--; //subtract 1 bullet from our current clip
			}else{
				//we do not have ammo, maybe play an audio clip that says I DO NOT HAVE AMMO! or NO AMMO!
				Debug.Log ("Reload you noob!");	
			}
		}else{
			//we are writing the reload here, in the else statement of left click...we dont want to allow them to reload if they are firing!
			//if we want to allow that, we can put this if outside
			if (Input.GetKeyDown (KeyCode.R)){
				if (ammoInCurrentClip<clipSize){
					ammoInCurrentClip=clipSize;
				}
			}
		}
		
		
	}
}

And here is a more realistic approach.

Simple Gun:
Unlimited Ammo
No Partial Reloads

Gun:
Maximum Ammo Limitations (Could be set to 999999) if you want unlimited
Partial Reloading due to Ammo Limitations
Empty Clip Detection
No More Ammo Detection

using UnityEngine;
using System.Collections;

public class Gun : MonoBehaviour {
	//these really should be private, however, im leaving them as public
	//for assignment in the inspector
	public int clipSize=8; //8 bullets per clip/magazine
	public int ammoInCurrentClip=0; //ammo in our current clip
	
	//technically, this should possibly be stored in the character object if they are using different guns
	//but lets assume 1 gun, so we can track ammo here
	//i have made these public so you can view them in the inspector as you fire youre gun
	//you should read on public/private and learn when to use what
	//technically these should be private as we dont want other scripts messing around with these 2 variables - the yre sort of used internally
	//by this class
	
	public int maxAmmo=80; //this is just used to cap bullets (e.g if you want the gun to only hold 80 bullets)
	public int currentAmmo=0;
	
	
	private float bulletSpeed=100000f;//speed the bullet travels at
	
	public GameObject bulletPrefab; //assign this variable from the inspector
	private Transform firingPoint;
	
	// Use this for initialization
	void Start () {
		//set our current ammo to our max ammo (start with a full gun)
		currentAmmo=maxAmmo;
		
		//alternatively - start with an empty gun and make the character collect bullets!
		//or start with a limited amount of ammo...currentAmmo=16 ...2clips
		
		//subtract clipsize (8) from our current ammo store - this means currentAmmo is now 72
		currentAmmo-=clipSize; 
		
		//add our clipsize into current clip - we start w ith a full clip right?! :smile:
		ammoInCurrentClip=clipSize;
		
		//so we now have 80 bullets - 8 in our clip, 72 in our currentAmmo (..lets say this is our ammo pack!)
		
		//get a reference to our firing point
		firingPoint=transform.Find ("FiringPoint"); //find the child FiringPoint of the gameobject this script is attached to (a gun)
	}
	
	// Update is called once per frame
	void Update () {
		//if the user has left clicked
		if (Input.GetMouseButtonDown (0)){
			
			//if we have ammo in the current clip, fire
			if (ammoInCurrentClip>0){
				//Instantiate our bullet prefab at the position and rotation of the firingpoint
				GameObject bullet=(GameObject)GameObject.Instantiate(bulletPrefab,firingPoint.position,firingPoint.rotation) as GameObject;
				
				//add force in the transform.forward direction (this is a normalized vector pointing in the direction the gun is facing)
				//The forward vector is the BLUE arrow in your scene preview
				//Example if the blue arrow was facing in the positive X direction this would be (1,0,0) 
				//You can use Debug.Log (transform.forward); if you want to see these values
				bullet.rigidbody.AddForce (transform.forward*(bulletSpeed*Time.deltaTime));
				
				// currentAmmo-- is a shortcut for currentAmmo=currentAmmo-1
				ammoInCurrentClip--; //subtract 1 bullet from our current clip
			}else{
				if (currentAmmo>0){
					//we do not have ammo, maybe play an audio clip that says I DO NOT HAVE AMMO! or NO AMMO!
					Debug.Log ("Reload you noob!");	
				}else{
					Debug.Log ("No More Bullets!");	
				}
			}
		}else{
			//we are writing the reload here, in the else statement of left click...we dont want to allow them to reload if they are firing!
			//if we want to allow that, we can put this if outside
			if (Input.GetKeyDown (KeyCode.R)){
				if (ammoInCurrentClip<clipSize){
					int bulletsToRefill=clipSize-ammoInCurrentClip; //if we reload after 2 shots, this will be 8-6 (2 bullets)
					
					//if our current ammo is greater than or equal to our bullets to refill
					//Example: 2 shots fired (bulletsToRefill is now 2), 72 Current Ammo. 72>=2, so we will just refill our clip
					if (currentAmmo>=bulletsToRefill){
						ammoInCurrentClip+=bulletsToRefill; //add these bullets to the clip
						currentAmmo-=bulletsToRefill; //substract the bullets from our ammo store
					}else{
					   //our current ammo does not have enough to completely refill the clip...
					   //lets say our current ammo was 2 and we needed to refill 5 bullets
					   //we will just add whatever is left in current ammo to t he clip, so if you have 3 bullets in  your clip
					   //and 2 current Ammo, and you reload, your clip now has 5 bullets, and ur current ammo is now 0
						ammoInCurrentClip+=currentAmmo;
						currentAmmo=0; //no more ammo
					}
				}
			}
		}
		
		
	}
}

Anyhow…in terms of your ORIGINAL code the issue you were having was that you end your class with } and then you define methods for that class.

class definitions look like this

class MyGameObject : MonoBehaviour{
   public int var1; 
   public int var2;

   void Update(){

   }  // } bracketcloses update method

  void Start(){

  } // } bracket closes start method
} // } bracket closes class

When you write code i recommend always opening / closing brackets IMMEDIATELY.

Example when you are writing the following:

void Start(){
     int x=1;
}

I would write it like this: type … void Start(){ then hit enter twice, type }, hit up arrow then tab/space to indent your line and then start typing…trust me, doing stuff like this (especially when you have nested statements inside nested statements inside nested statements will save you A LOT of headaches.

good luck!! :slight_smile: enjoy the scripts iw rote for you - free to use even for commercial have @ it.