I'm trying to make an FPS game in Unity and have setup a RayCast shooting system. Whenever I shoot, I have it set where the gun ammo count should decrement by 1. However, every time I left-click it decrements the ammo count by a random number and I have no idea why. The counter decreases by 8, by 12, by 10, 9, just random integers. It should only be decreasing by 1 right?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public int id;
float nextTimeToFire;
[SerializeField] int currAmmo;
float reloadSpeed = 1;
public GameObject gameController;
public ItemDatabase database;
public Camera mainCam;
void Start()
{
gameController = GameObject.FindGameObjectWithTag ("GameController");
database = gameController.GetComponent<ItemDatabase> ();
mainCam = Camera.main;
id = GetComponent<ItemID> ().itemID;
currAmmo = database.weapons[id].maxAmmo;
}
void Update()
{
if(currAmmo <= 0)
{
StartCoroutine(Reload());
return;
}
if(Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
Shoot();
}
}
void Shoot()
{
currAmmo--;
RaycastHit hit;
if(Physics.Raycast(mainCam.transform.position, mainCam.transform.forward, out hit, database.weapons [id].range))
{
nextTimeToFire = Time.time 1f/database.weapons [id].fireRate;
if (hit.transform.tag == "Enemy")
{
Debug.Log (hit.transform.name);
CharacterStats enemyStats = hit.transform.GetComponent<CharacterStats> ();
enemyStats.TakeDamage (database.weapons [id].damage);
Debug.Log (database.weapons [id].damage);
}
}
}
IEnumerator Reload()
{
yield return new WaitForSeconds (reloadSpeed);
currAmmo = database.weapons [id].maxAmmo;
}
}
CodePudding user response:
It's look like you showing the ammo count from a database. The code here should decrease the index by 1 so did you check the database indexes. It may be the issue that the ammo count in the database is out of order. My opinion though...
CodePudding user response:
It's not random number, it the frame amount you held the mouse button down, try GetButtonDown or add condition which restricts shooting every frame when mouse is held down
CodePudding user response:
I believe your not resetting nextTimeToFire in time and shoot is being called multiple time in update while Fire1 is pressed. Try resetting nextTimeToFire
and then call Shoot();
You could also consider using if (Input.GetButtonDown("Fire1"))
Call this function from the Update function, since the state gets reset each frame. It will not return true until the user has released the key and pressed it again. You could set a bool shooting = true;