Hey all,
I’m having a tricky issue here that I got myself into, and I’ve been trying to wrap my head around it for hours, but feel like I’ve given myself tunnel vision now, so I could use some fresh eyes. Here’s my code:
Basically, I have a setup where my weapon uses a bool to check if it can shoot or not, and I run a coroutine in between shots to give it a “shotgun” feel. When I implemented a pause menu, I had to try and disable my shooting during pause. Problem is, I put the canShoot bool = true (if not paused) in update. So either my shotgun now fires for every click (because it’s always true) OR it doesnt fire at all after pausing. I feel like there is either an easy fix or I have to really re do this system. Any ideas?
Try this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shotgun : MonoBehaviour
{
public float ReloadTime = 2.5f;
public int Bullets = 9;
public bool IsReloading = false;
private bool _isPaused = false;
private bool _hasBullets => Bullets > 0;
void Update()
{
HandleShooting();
HandleReloading();
// NOTE THE PAUSE LOGIC SHOULDNT GO HERE THIS IS JUST FOR TESTING
if(Input.GetKeyDown(KeyCode.P))
{
_isPaused = !_isPaused;
Debug.Log(_isPaused ? "Paused" : "Unpaused");
Time.timeScale = _isPaused ? 0 : 1;
}
}
private void HandleShooting()
{
if(Input.GetKeyDown(KeyCode.Space) && _hasBullets && !IsReloading)
{
Debug.Log("BANG!!");
Bullets--;
}
}
private void HandleReloading()
{
if(Input.GetKeyDown(KeyCode.R) && !IsReloading)
{
StartCoroutine(Reload());
}
}
IEnumerator Reload()
{
Debug.Log("Reloading!");
IsReloading = true;
yield return new WaitForSeconds(ReloadTime);
Bullets = 9;
IsReloading = false;
Debug.Log("Reloaded!");
}
}