- Home /
C# Switch Weapon
I'm currently making a 3D Multiplayer FPS. Right now I am working on making more weapons and then having the game switch the weapon you're holding when you get a new one. The problem is: I look on all tutorials to see how to do this, but they are all in JavaScript. I try to keep my code in C# to keep it simple, and rarely do I use Java. Is there a way I can switch weapons without using JavaScript?
P.S. In another code, I have the fire rate and damage variables, and I was thinking about using a weaponID variable to control the actual weapon visual.
Answer by hav_ngs_ru · Mar 10, 2015 at 03:13 PM
Is there a way I can switch weapons without using JavaScript?
There are at least two ways:
to write your own script in C#.
to port the sript you like from JS to C#.
Answer by DasFloX · Mar 10, 2015 at 03:44 PM
You just need to have the gameObjects of your weapons, that should be children of your Player, in an array or a list, so you can cycle through them. And you should also have a class for the weapons, so you can access their values more easy.
[System.Serializable]
class Weapon{
public GameObject model;
public float fireRate;
public int ammo;
...
}
The Array:
public Weapon[] weapons = new Weapon[numberOfWeaponsinInventory];
public int currentWeapon = 0;
public void start(){
//Disabling all Weapons first
foreach(Weapon i in weapons){
i.model.SetActive(false);
}
//Enabling the starting weapon
weapons[currentWeapon].model.SetActive(true);
}
public void Update(){
if(Input.GetAxis("Mouse ScrollWheel")>0){
//Disabling all Weapons first
foreach(Weapon i in weapons){
i.model.SetActive(false);
}
currentWeapon++;
weapons[currentWeapon].model.SetActive(true);
}
if(Input.GetAxis("Mouse ScrollWheel")<0){
//Disabling all Weapons first
foreach(Weapon i in weapons){
i.model.SetActive(false);
}
currentWeapon--;
weapons[currentWeapon].model.SetActive(true);
}
}
You should also adjust your Fire Rate and stuff to the one of the chosen weapon given in the array. Thats just an example code, you should adjust to your needs. Hope it helps, FlomoN
Your answer
Follow this Question
Related Questions
FireWeapon.cs not working 2 Answers
pause for dastardly bannana 1 Answer
HDRP Camera weapon layer 1 Answer
change weapon only one player in network 0 Answers