Hey, I’m quite new to Unity/C# and I’ve recently started venturing into building my own games with no tutorial help. I set up a script to reload when the player presses the reload button, or when their remaining bullets are less than 0. I set up an if/else if statement to only call Reload() once every time the bullets go below 1, which looks like this:
If/Else If:
if (bulletCount < 1 && shouldReload == true)
{
Reload();
shouldReload = false;
}
else if (bulletCount >= 1 && shouldReload == false)
{
shouldReload = true;
}
Whenever Reload() is called through this if statement, the audio source in it doesn’t play.
The Reload() method:
void Reload()
{
isReload = true;
source.clip = reload;
source.Play(0);
reloadTime = source.clip.length;
Invoke("Start", reloadTime);
}
but whenever Reload() is called from
Reload button check:
if (Input.GetButtonUp("Reload"))
{
Reload();
Debug.Log("Reloading!");
}
the audio plays fine.
The whole script together:
using UnityEngine;
using UnityEngine.UI;
public class playerController : MonoBehaviour
{
public float speed = 10f;
public Transform player;
public bool isShooting = false;
public float fireDelay;
private float timeUntilShoot;
public Vector3 move;
public int health = 200;
public Text healthText;
public GameObject endScreen;
public GameObject crosshair;
public bool isReload;
public float reloadTime;
public AudioClip reload;
private AudioSource source;
public int magSize = 30;
public int bulletCount = 30;
private bool shouldReload = true;
void Start()
{
bulletCount = magSize;
source = player.GetComponent<AudioSource>();
timeUntilShoot = fireDelay;
Time.timeScale = 1;
isReload = false;
}
void Update()
{
timeUntilShoot -= Time.deltaTime;
Vector3 move = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
transform.Translate(move * Time.deltaTime * speed, Space.World);
healthText.text = health.ToString("0HP");
if (Input.GetButton("Fire1") && timeUntilShoot < 0 && isReload == false)
{
isShooting = true;
timeUntilShoot = fireDelay;
bulletCount--;
}
else
{
isShooting = false;
}
if (health < 1)
{
endScreen.SetActive(true);
crosshair.SetActive(false);
}
if (Input.GetButtonUp("Reload"))
{
Reload();
Debug.Log("Reloading!");
}
if (bulletCount < 1 && shouldReload == true)
{
Reload();
shouldReload = false;
}
else if (bulletCount >= 1 && shouldReload == false)
{
shouldReload = true;
}
void Reload()
{
isReload = true;
source.clip = reload;
source.Play(0);
reloadTime = source.clip.length;
Invoke("Start", reloadTime);
}
}
}
It’s also important to note that I know that Reload() is being called because isReload becomes equal to true in the inspector and I am unable to shoot.
Thanks