Trying to convert weapon switcher to switch statement.

I’m working on an FPS game and made a weapon switcher. The problem is that it’s made entirely of “if else” statements. Can someone please tell me how to convert this to a switch statement?

Current code:

if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            SwitchToPistol();
        }
        else if (Input.GetKey(KeyCode.Alpha2))
        {
            SwitchToAR();
        }
        else if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            SwitchToMelee();
        }
        else if(Input.GetKeyDown(KeyCode.Alpha4))
        {
            SwitchToPortals();
        }

Unfortunately there is not a single variable you are “switching” on in this example so you can’t really convert this to a switch statement. It’s actually 4 distinct conditions you are checking, not the value of a single condition.

1 Like

You can’t trivially, but you don’t really need the else either, which would clean it up.

Another consideration is that you may wish to divorce the notion of gathering input (ie. what key logically does what), with actually processing the input.

In other words, when certain keys are hit, adjust certain internal “input from this frame” variables.

This lets you easily add other input methods, such as touch or Kinect or VR gesture or whatever, and they all just modify those frame input values.

Finally when all input is gathered for a frame, separately have the consumers of the input process it and decide what to do with it. Breaking input gathering apart from actioning is good.

1 Like

Why is that a problem? switch statements aren’t superior to if/else chains. If anything, I find them quite limiting and in most situations the syntax is pretty annoying. If you’re choosing between strings it has some performance benefits but those are minimal.

If you want to clean up the code, what you should be doing is creating a data structure that links your keypresses to each weapon. This data structure can be easily extended to add new weapons without adding new code in your selection script. For example:

[Serializable] public class Weapon {
public KeyCode selectionKey;
public string weaponName;
// any other weapon info can go here too, including references to GameObjects to swap in/out, sprite for selection icons, etc
}

public Weapon[] allWeapons;
public int currentWeaponIndex = 0;

void Update() {
for (int w=0; w<allWeapons.Length; w++) {
if (Input.GetKeyDown(allWeapons[w].selectionKey) ) {
currentWeaponIndex = w;
}
}
}
1 Like

Oh well :confused: