Weapon Shoot Bug

I have a bug where when I switch weapons, I can shoot one bullet from the previous weapon.

Any help on fix?

Here is the code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WeaponSwitching : MonoBehaviour
{

    [Header("References")]
    [SerializeField] private Transform[] weapons;

    [Header("Keys")]
    [SerializeField] private KeyCode[] keys;

    [Header("Settings")]
    [SerializeField] private float switchTime;

    private int selectedWeapon;
    private float timeSinceLastSwitch;

    private void Start() {
        SetWeapons();
        Select(selectedWeapon);

        timeSinceLastSwitch = 0f;
    }

    private void SetWeapons() {
        weapons = new Transform[transform.childCount];

        for (int i = 0; i < transform.childCount; i++)
            weapons[i] = transform.GetChild(i);

        if (keys == null) keys = new KeyCode[weapons.Length];
    }

    private void Update() {
        int previousSelectedWeapon = selectedWeapon;

        for (int i = 0; i < keys.Length; i++)
            if (Input.GetKeyDown(keys[i]) && timeSinceLastSwitch >= switchTime)
                selectedWeapon = i;

        if (previousSelectedWeapon != selectedWeapon) Select(selectedWeapon);

        timeSinceLastSwitch += Time.deltaTime;
    }

    private void Select(int weaponIndex) {
        for (int i = 0; i < weapons.Length; i++)
            weapons[i].gameObject.SetActive(i == weaponIndex);

        timeSinceLastSwitch = 0f;

        OnWeaponSelected();
    }

    private void OnWeaponSelected() {  }
}

Hello,

The first time SetWeapon is ran (on Start), you instantiate the field keys. However here you don’t instantiate each key code to a distinct value, instead you create an array of KeyCode, and if I’m not mistaken this is an enum so it defaults to the enum variant corresponding to 0.

Try to log the array keys and see if indeed they all have the same value.

It’s a bit odd to add key bindings this way anyway, if what you meant was that typing key n means switching to weapon n, you should instead look up what the key code for 1, 2, 3 … are and bind them instead.

Hope this helps,
Simon