- Home /
Making Weapon Switching Code more effective.
Hello. I made a simple weapon switching code for my character.
I want to ask, there is a way to make this code more effective?
This is my code:
if (Input.GetKeyDown ("1"))
{
weaponID = 1;
}
if (Input.GetKeyDown ("2"))
{
weaponID = 2;
}
if (Input.GetKeyDown ("3"))
{
weaponID = 3;
}
I am using JS.
You want to make it more effective how? Faster compiling of the code ? Or do you want a for loop since the weapon is linked to the key directly?
Answer by wannabee · Dec 17, 2012 at 08:49 PM
You could do something like:
function changeWeapon() {
for (var i : int = 1; i<=3; i++) {
if(Input.GetKeyDown(i.ToString())) {
weaponID = i;
return;
}
}
}
If you would like...
It won't be more efficient in the sense that it won't run faster, but I do like this coding style better, even though it might hurt readability a bit. Also, now it's easy to add more weapons, just change that number 3... :)
Answer by MirekPluta · Dec 17, 2012 at 08:49 PM
What exactly do you mean by "more effective" ? If you mean performance, then you'll get little improvement when instead of 3 separate if statements you use if-elseif-elseif statement.
if (Input.GetKeyDown ("1"))
{
weaponID = 1;
}
else if (Input.GetKeyDown ("2"))
{
weaponID = 2;
}
else if (Input.GetKeyDown ("3"))
{
weaponID = 3;
}
You could also create some dictionary containing key-weapon pairs and iterate it to check for weapon switch.
var key_weapon = { "1" : 1, "2" : 2, "3" : 3};
for( kvp in key_weapon)
{
if(Input.GetKeyDown(kvp.Key.ToString()))
{
weaponId = kvp.Value;
}
}
Answer by Karsnen_2 · Dec 17, 2012 at 08:35 PM
I do not think there is much you could do with what you already have. While developing, optimizing could also be a devil. So try to be effective or optimize your code only when your target platform only demands. Else just forget it.
READABLE CODE :
The best way that you could do, by which I mean to say is make it clean to read is -> Create a method that would receive int as the parameter. Use this int in a switch case to change weapon. On your update method call the method by passing the appropriate parameter.
CODE : It is in C#.
void Update ()
{
if (Input.GetKeyDown ("1"))
ChangeWeapon(1);
if (Input.GetKeyDown ("2"))
ChangeWeapon(2);
if (Input.GetKeyDown ("3"))
ChangeWeapon(3);
}
void ChangeWeapon (int i)
{
switch (i)
{
case 1 :
// Switch to the required weapon
break;
case 2:
// Switch to the required weapon
break;
case 3:
// Switch to the required weapon
break;
default:
break;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613085550im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How Does Weapon Selection Work In-Game? 0 Answers
Weapon Switching 2 Answers
WeaponScript not working 0 Answers
Weapon Switching 2 Answers