- Home /
Cycle weapons with only ONE key press (spacebar)
Trying to use the spacebar ONLY to cycle through 4 weapons.
The following script seems to be pretty straight forward but is stuck on SelectWeapon(0) at runtime. Yes, it's a tweeked version of the standard FPS tutorial script.
Any thoughts are appreciated.
function Start () { SelectWeapon (0); }
function Update () {
if (Input.GetButton ("Fire1"))
BroadcastMessage("Fire");
if (Input.GetKeyDown("space") && SelectWeapon == 0)
{
SelectWeapon (1);
}
else if(Input.GetKeyDown("space") && SelectWeapon == 1)
{
SelectWeapon (2);
}
else if (Input.GetKeyDown("space") && SelectWeapon == 2)
{
SelectWeapon (3);
}
else if (Input.GetKeyDown("space") && SelectWeapon == 3)
{
SelectWeapon (0);
}
}
function SelectWeapon (index : int) { for (var i=0;i<transform.childCount;i++)
{ if (i == index) transform.GetChild(i).gameObject.SetActiveRecursively(true); else transform.GetChild(i).gameObject.SetActiveRecursively(false); } }
Answer by 3dDude · Jul 28, 2010 at 01:01 AM
this will work :)
private var selectedWeapon : int = 0; function Start () { SelectWeapon (0); }
function Update ()
{
if (Input.GetButton ("Fire1"))
BroadcastMessage("Fire");
if (Input.GetKeyDown("space"))
{
selectedWeapon++;
if(selectedWeapon == transform.childCount){
selectedWeapon = 0;
}
SelectWeapon (selectedWeapon);
}
}
function SelectWeapon (index : int)
{
for (var i=0;i<transform.childCount;i++)
{
if (i == index){
transform.GetChild(i).gameObject.SetActiveRecursively(true);
}
else{
transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
}
hope this works! :D
I had the notion from the start that this could be done with one IF statement for Get$$anonymous$$eyDown, including the selectedWeapon++; part! The bits of code you gave me was exactly what I needed, the final pieces to my maddening puzzle! WOR$$anonymous$$ED EXACTLY AS NEEDED, THAN$$anonymous$$ YOU SO $$anonymous$$UCH!!!
still works perfectly, thanks, just what i was looking for :D
Answer by ADITYA GOUR · Sep 17, 2012 at 06:44 PM
hello Guyss!!. I copy the same script in my game, it works well but the shooting, switching, weapon realoding is very fast like 100times of normal working. when i check weapons individually then they work well. i think your script has need of 'Time.deltaTime' function.. I m a noob in programming , I don't know where it will be put.... in the script ....or any other solution.Anybody help me to fix this problem. i m waiting for your answer... and Thanx in advance... sorry for the weak grammar.
Your answer
Follow this Question
Related Questions
Switch from one player to another. 5 Answers
I'm trying to make a weapon pickup script but can't quite get it to work. 0 Answers
Switching Between Weapons? 1 Answer
switch weapons script not working? 2 Answers
How to switch between 2d characters? 0 Answers