Can someone help me with a problem I ran into. Lets say Gun1
has 10 bullets and Gun2
has none. When I switch to Gun2
, I can shoot only one bullet as if it registers the weapon switched when I click. I’ll send the scripts
WeaponSwitching.cs
using UnityEngine;
public class WeaponSwitching : MonoBehaviour
{
public int selectedWeapon = 0;
private void Start()
{
SelectWeapon();
}
private void Update()
{
int previousSelectedWeapon = selectedWeapon;
if (Input.GetAxis("Mouse ScrollWheel") > 0f) {
if (selectedWeapon >= transform.childCount - 1)
selectedWeapon = 0;
else
selectedWeapon++;
}
if (Input.GetAxis("Mouse ScrollWheel") < 0f) {
if (selectedWeapon <= 0)
selectedWeapon = transform.childCount - 1;
else
selectedWeapon--;
}
if (Input.GetKeyDown(KeyCode.Alpha1)) {
selectedWeapon = 0;
}
if (Input.GetKeyDown(KeyCode.Alpha2) && transform.childCount >= 2) {
selectedWeapon = 1;
if (selectedWeapon == 1) {
Debug.Log("Gun2");
}
}
if (previousSelectedWeapon != selectedWeapon) {
SelectWeapon();
}
}
private void SelectWeapon()
{
int i = 0;
foreach (Transform weapon in transform) {
if ( i == selectedWeapon )
weapon.gameObject.SetActive( true );
else
weapon.gameObject.SetActive( false );
i++;
}
}
}
Gun.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
[Header("References")]
[SerializeField] private GunData gunData;
[SerializeField] private Transform cam;
float timeSinceLastShot;
private void Start()
{
PlayerShoot.shootInput += Shoot;
PlayerShoot.reloadInput += StartReload;
}
private void OnDisable() =>gunData.reloading = false;
public void StartReload()
{
if(!gunData.reloading && this.gameObject.activeSelf) {
StartCoroutine(Reload());
}
}
private IEnumerator Reload()
{
gunData.reloading = true;
yield return new WaitForSeconds(gunData.reloadTime);
gunData.currentAmmo = gunData.magSize;
gunData.reloading = false;
}
private bool CanShoot() => !gunData.reloading && timeSinceLastShot > 1f / (gunData.fireRate / 60f);
public void Shoot()
{
if (gunData.currentAmmo > 0) {
if (CanShoot()) {
if (Physics.Raycast(cam.position, cam.forward, out RaycastHit hitInfo, gunData.maxDistance)) {
Debug.Log(hitInfo.transform.name);
IDamageable damageable = hitInfo.transform.GetComponent<IDamageable>();
damageable?.TakeDamage(gunData.damage);
Debug.Log("Gun1");
}
gunData.currentAmmo--;
timeSinceLastShot = 0;
}
}
}
private void Update()
{
timeSinceLastShot += Time.deltaTime;
Debug.DrawRay(cam.position, cam.forward * gunData.maxDistance);
}
}
PlayerShoot.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerShoot : MonoBehaviour
{
public static Action shootInput;
public static Action reloadInput;
[SerializeField] private KeyCode reloadKey;
private void Update()
{
if (Input.GetMouseButton(0))
shootInput?.Invoke();
if (Input.GetKeyDown(reloadKey))
reloadInput?.Invoke();
}
}