- Home /
How to make a weapon index?
I am building off of the FPS tutorial script for changing weapons, such as "blah blah blah, change SelectWeapon(2) if 2 is pressed and all that. Then I have the SelectWeapon index code from the FPS tutorial also, but what I did is edit the code to include 5 weapons, not just 2. But the thing is, i dont know how to assign the index variable of the first weapon to SelectWeapon(1) or whatever.
Im using the exact same code from the FPS tutorial, I just dont know to how to set the weapons I have to the index values accordingly. :)
Answer by · Sep 16, 2010 at 03:00 AM
Hey Nick, welcome to UnityAnswers.
The SelectWeapon() function uses the GetChild() function to find the 'children' objects of the object that the SelectWeapon script is attached to. I've added comments to the script below to explain.
function SelectWeapon (index : int)
{
for (var i=0;i<transform.childCount;i++) // loop through all the 'children'
{
// if the desired weapon value is the same as current child index value
if (i == index)
{
// Activate the selected weapon
transform.GetChild(i).gameObject.SetActiveRecursively(true);
}
else // otherwise
{
// Deactivate all other weapons
transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
}
As a result, you can't explicitly 'assign the index variable of the first weapon' - rather, you set the weapon to a child of the GameObject that this script is attached to. I'd assume the GetChild() function sorts by name, so you could just name the weapons "0_Fists", "1_Pistol", etc.
Duck's answer to a similar question on 'Weapon Switching' explains how to extend the if/else in the Update() loop, so pressing '3' will select the 3rd weapon, and so on.
Hope this helps!
So $$anonymous$$arowi, Nick again, /i changed all the child objects, which are the weapons,to be named 1_$$anonymous$$elee, 2_Deagle, etc. but the issue is still arising.Any other ideas of how the index will sort?
Your answer
Follow this Question
Related Questions
FPS game: weapons 2 Answers
unlocking weapon (fps) 1 Answer
The Variable has not been assigned. 1 Answer
FireWeapon.cs not working 2 Answers