Hi there,
I have a weapon switching script which I got from: Weapon Switching - Unity Tutorial - YouTube
I’m trying to add a delay between weapon switching but having trouble with it. Here’s the script:
using UnityEngine;
public class PlayerWeapons : MonoBehaviour
{
public int currentWeapon = 0;
public float switchDelay = 0.5f;
public float railSwitchDelay = 1.0f;
private float nextSwitch;
void Start()
{
SelectWeapon();
}
void Update()
{
int previousWeaponSelected = currentWeapon;
// if scroll wheel up is pressed
if (Input.GetAxis("Mouse ScrollWheel") > 0f)
{
// if currentWeapon goes above the amount of weapons, go back to the first weapon, index 0
if (currentWeapon >= transform.childCount - 1)
currentWeapon = 0;
// otherwise, go to next weapon
else
currentWeapon++;
}
// if scroll wheel down is pressed
if (Input.GetAxis("Mouse ScrollWheel") < 0f)
{
// if currentWeapon is already at 0, go to the last child (weapon)
if (currentWeapon <= 0)
currentWeapon = transform.childCount - 1;
// otherwise, go to previous weapon
else
currentWeapon--;
}
// if number 1 is pressed
if (Input.GetKeyDown(KeyCode.Alpha1))
{
currentWeapon = 0;
}
// if number 2 is pressed
if (Input.GetKeyDown(KeyCode.Alpha2))
{
currentWeapon = 1;
}
// if number 3 is pressed
if (Input.GetKeyDown(KeyCode.Alpha3))
{
currentWeapon = 2;
}
// if number 4 is pressed
if (Input.GetKeyDown(KeyCode.Alpha4))
{
currentWeapon = 3;
}
if (previousWeaponSelected != currentWeapon && Time.time > switchDelay)
{
nextSwitch = Time.time + switchDelay;
SelectWeapon();
}
}
void SelectWeapon()
{
// ensure all weapon lines are disabled
GameObject[] weapons;
weapons = GameObject.FindGameObjectsWithTag("Weapon");
foreach (var weapon in weapons)
{
weapon.BroadcastMessage("DisableLine", SendMessageOptions.DontRequireReceiver);
}
// ensure the lightning hum sound stops when switching weapons
FindObjectOfType<AudioManager>().Stop("LightningHum");
// disable all weapons except the current
int i = 0;
// loop through all child objects of the object which has this script
foreach (Transform weapon in transform)
{
// if the first object is equal to 0, set the first object to active and set the other objects to inactive
if (i == currentWeapon)
weapon.gameObject.SetActive(true);
else
weapon.gameObject.SetActive(false);
i++;
}
}
}
The delay part which I have tried to implement is this bit:
if (previousWeaponSelected != currentWeapon && Time.time > switchDelay)
{
nextSwitch = Time.time + switchDelay;
SelectWeapon();
}
But it’s not working, the weapons still switch instantly. The logic must be flawed, can anyone help me out? P.S. I have tried adding the same logic to each of the “if number key pressed” statements but that doesn’t work either!
Thanks for any help!