- Home /
Gun with ammo help
I need help with my gun script. I have been searching all over the internet but have not been able to find any help.
I have the gun working fairly good but when I try to make my bullets change then it does not work properly. My bullet count go down but when I press "r" for reloading then it does not fill up my bullets or lose a clip. if anyone could help I would be most grateful. If any other tips about my script I would also be very happy :)
public Ray ray;
public RaycastHit hit;
public GameObject BulletMark;
//public GameObject GunEffect;
public float FireRate;
public float GunRecoil = 10;
int Bullets = 8;
int AmmoLeft = 3;
public GUIText Ammo;
public GUIText AmmoClips;
void Update () {
if(Input.GetMouseButtonDown(0)&& Bullets>0){
//Start Shooting
InvokeRepeating("Shoot", 0.01f, 1/FireRate);
//GunEffect.active = true;
}
if(Input.GetMouseButtonUp(0)){
//Stop Shooting
CancelInvoke("Shoot");
//GunEffect.active = false;
}
}
void Shoot(){
//Normal Raycast //Add a random value to mouse position(r
ray = Camera.main.ScreenPointToRay(Input.mousePosition+Random.insideUnitSphere*GunRecoil);
if(Physics.Raycast(ray, out hit, 1000)){
//Declear new GameObject variable
GameObject BulletHole;
//Create the shootmark prefab at the hit point
BulletHole = Instantiate (BulletMark, hit.point+(hit.normal*0.001f), transform.rotation) as GameObject;
//Rotate the created object at the face of the normal LookAt (hit.point+hit.normal)
BulletHole.transform.LookAt(hit.point+hit.normal);
BulletHole.transform.parent=hit.transform;
hit.transform.gameObject.SendMessage("Hit", 5, SendMessageOptions.DontRequireReceiver);
}
Bullets = Bullets-1;
Ammo.text = Bullets.ToString();
if(Bullets==0){
//CancelInvoke("Shoot");
}else{
if (Input.GetKeyDown("r")&& AmmoLeft>0){
Bullets = Bullets+8;
AmmoLeft = AmmoLeft-1;
InvokeRepeating("Shoot", 0.01f, 1/FireRate);
}
}
}
void OnTriggerEnter (Collider AmmoCrate){
if(AmmoCrate.gameObject.name=="MoreBullets"){
Destroy (AmmoCrate.gameObject);
AmmoLeft = AmmoLeft + 2;
AmmoClips.text = AmmoLeft.ToString();
}
}
}
Answer by robertbu · Jul 20, 2013 at 04:57 PM
I'm not sure your desired behavior is here. You've put put your reload logic inside shoot, and you are using 'GetKeyDown()'. Combine the two and it means your reload logic will only work if the Shoot() is being called on exactly the same frame that the 'r' key goes down. These happening at the same time is unlikely. Also calling InvokeRepeating() here is strange. You could replace GetKeyDown() with GetKey(), but I think you want to move this logic into Update() so that the check for reload happens each frame regardless if the user is shooting or not.
If you question is answered, please click on the checkmark to close it out. Thanks.
Your answer
Follow this Question
Related Questions
Reload After Magazine Is Empty 2 Answers
Gun - Ammo , reloading and UI problem. 1 Answer
Ammo Script 1 Answer