x


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. :)

more ▼

asked Sep 15 '10 at 10:47 PM

Padges gravatar image

Padges
88 24 29 33

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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!

more ▼

answered Sep 16 '10 at 03:00 AM

Marowi gravatar image

Marowi
4.9k 4 14 53

So Marowi, Nick again, /i changed all the child objects, which are the weapons,to be named 1_Melee, 2_Deagle, etc. but the issue is still arising.Any other ideas of how the index will sort?

Jan 11 '11 at 05:53 PM user-4565 (google)
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1175
x379
x220
x65

asked: Sep 15 '10 at 10:47 PM

Seen: 1209 times

Last Updated: Sep 15 '10 at 10:47 PM