- Home /
Question by
Fonics · Jul 18, 2020 at 03:36 AM ·
inputkeycodeweapon systemweaponchanging
More efficient way to do weapon switching?
I am currently working on a script for handling weapon switching and I wanted to know if there was a more efficient way to do this than 9 if statements in the Update function.
My current code:
if (Input.GetKeyDown(KeyCode.Alpha1))
{
currentWeapon = 0;
setActiveWeapon(currentWeapon);
}
if (Input.GetKeyDown(KeyCode.Alpha2))
{
currentWeapon = 1;
setActiveWeapon(currentWeapon);
}
if (Input.GetKeyDown(KeyCode.Alpha3))
{
currentWeapon = 2;
setActiveWeapon(currentWeapon);
}
if (Input.GetKeyDown(KeyCode.Alpha4))
{
currentWeapon = 3;
setActiveWeapon(currentWeapon);
}
if (Input.GetKeyDown(KeyCode.Alpha5))
{
currentWeapon = 4;
setActiveWeapon(currentWeapon);
}
if (Input.GetKeyDown(KeyCode.Alpha6))
{
currentWeapon = 5;
setActiveWeapon(currentWeapon);
}
if (Input.GetKeyDown(KeyCode.Alpha7))
{
currentWeapon = 6;
setActiveWeapon(currentWeapon);
}
if (Input.GetKeyDown(KeyCode.Alpha8))
{
currentWeapon = 7;
setActiveWeapon(currentWeapon);
}
if (Input.GetKeyDown(KeyCode.Alpha9))
{
currentWeapon = 8;
setActiveWeapon(currentWeapon);
}
Comment
Answer by Namey5 · Jul 18, 2020 at 05:27 AM
Input is a bit weird to work with in Unity, so the only way I could think would be to wrap this stuff in a loop, i.e;
KeyCode[] keys = new KeyCode[9]
{
KeyCode.Alpha1,
KeyCode.Alpha2,
KeyCode.Alpha3,
KeyCode.Alpha4,
KeyCode.Alpha5,
KeyCode.Alpha6,
KeyCode.Alpha7,
KeyCode.Alpha8,
KeyCode.Alpha9
};
for (int i = 0; i < 9; i++)
{
if (Input.GetKeyDown (keys[i]))
{
currentWeapon = i;
setActiveWeapon (currentWeapon);
}
}
Your answer

Follow this Question
Related Questions
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
How to Use Key Combinations with the Control-Key? 2 Answers
Best weapon system for multiplayer FPS? 0 Answers
Protected/private, KeyCode, Colliders and Large map Questions 2 Answers
Shift + KeyCode.Equals works in Unity Editor but not on WebGL build 0 Answers