- Home /
Question by
Getsumi3 · Jul 30, 2017 at 04:01 PM ·
c#fpsswitchswitch-case
Switch enum case on key pressed
Good day. I'm making a FPS game so I'm trying to make fireMode for weapons (semi, burst, auto) And I want to change my fireMode each time I press Input.GetKeyDown(KeyCode.V)
here is what I have
public class shoot : MonoBehaviour {
// a lot of variables
//fire mode
public enum FireMode
{
semi,
burst,
auto
}
public FireMode fireMode;
void Update(){
switch (fireMode) {
case FireMode.semi:
if (Input.GetMouseButtonDown (0)) {
ProjectileCount = 1;
TryFire ();
}
break;
case FireMode.burst:
if (Input.GetMouseButtonDown (0)) {
ProjectileCount = 3;
TryFire ();
}
break;
case FireMode.auto:
if (Input.GetMouseButton (0)) {
ProjectileCount = 1;
TryFire ();
}
break;
}
}
It is working fine when I set FireMode in Editor But I don't know how to make it change in runtime when pressing a key. thanks
Comment
Best Answer
Answer by UnityCoach · Jul 30, 2017 at 04:17 PM
Hi,
an enum is, under the hood, an int. So you can do the following :
if (Input.GetKeyUp (KeyCode.V))
{
int currentFireMode = (int)fireMode;
currentFireMode = currentFireMode == 2 ? 0 : currentFireMode+1; // replace 2 with the greater
fireMode = (FireMode)currentFireMode;
}
I would also add that you can optimise your switch case logic, by first checking if (Input.GetMouseButtonDown (0))
, then use the switch as it seems you're always using the same mouse button.
if (Input.GetMouseButtonDown (0))
{
switch (fireMode)
{
case FireMode.semi:
break;
case FireMode.burst:
break;
case FireMode.auto:
break;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612131530im_/https://answers.unity.com/themes/thub/images/avi.jpg)