Thank you for making the project smaller. My computer is rather slow.
I’ve just downloaded and tested your game, and I was able to recreate the problem in Unity 2023.1.14f1. I was not able to spot any problem, so I tried to identify a pattern. I focussed on the input via keyboard and ignored the mouse wheel.
Interestingly, weapon 1 (= the 2nd weapon) gets disabled only if I press 1-2-3-2. With 1-2-3-1-2 (after restarting the game), weapon 1 continues to work, so my best guess was that the weapon breaks if I go ‘back’. With 3 weapons, selecting weapon 0 again is always ‘back’ in regards to the sequence 0-1-2 (keys: 1-2-3).
Based on this, I checked the algorithm because I supected that the problem might be related to the indices. If 1-2-3-1-2 does not break the weapon at index 1 (key 2) but 1-2-3-2 does, maybe the code iterates over the weapons in an ascending order.
The first thing I did was to replace the two if
with else if
in the ProcessKeyInput() method. This does not have anything to do with the problem but it is good practice. If you used if
on purpose, ignore this part.
Since the only code that iterates over the weapons is SetWeaponActive(), I suspected that there might be a problem with the activation/deactivation of a weapon. For testing purposes, I simply added another loop in which I deactivated all weapons:
void SetWeaponActive()
{
foreach (Transform weapon in transform)
{
weapon.gameObject.SetActive(false);
}
int weaponIndex = 0;
foreach (Transform weapon in transform)
{
if(weaponIndex == currentWeapon)
{
weapon.gameObject.SetActive(true);
Debug.Log("set active weapon");
}
else
{
weapon.gameObject.SetActive(false);
}
weaponIndex++;
}
}
This fixed the problem for me.
Unfortunately, it is already late here, and I probably won’t have time on Monday and Thursday to check anything. However, I wanted to give you a quick workaround, so you will hopefully be able to continue working on your project.
Since deactivating all weapons solved the problem (for me), I assume that my guess was right. Of course, the two loops are not ‘beautiful’ but I’m sure you’ll be able to refactor the code yourself. By checking the values of the involved variables, you’ll probably also be able to figure out if my guess was right.
Your game looks promising, by the way. Keep it up!
See also: