- Home /
Weapon switching.
Hello I'm trying to code a way to switch weapons. I'm new to unity and am very confused. I have this from the fps tutorial and a bit of what I did.
#pragma strict
var wepNum : float = 0; var numOfWeps : float = 5;
function Start () {
}
function Update () { switchgun(wepNum);
if(Input.GetKeyDown("1")) { if(wepNum > 0) { wepNum--; } } if(Input.GetKeyDown("2")) { if(wepNum < numOfWeps) { wepNum++; } } } function switchgun(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); } }
but how would I switch weapon models? and I don't really understand what this does.
function switchgun(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); } }
For starters, I'm pretty sure 'wepNum' and 'numOfWeps' are both supposed to be integers, since they are for counting things. How much do you actually understand about how this script works?
I understand how most of it works. I just don't understand that last function. Also how would I switch models with each time I switch guns?
Answer by aldonaletto · Jan 12, 2012 at 03:15 AM
You must attach this script to an empty object and child the empty object to the camera, then child all weapon models to this empty object, and adjust each one to the desired position/rotation. The function switchgun(index) just deactivates all weapons, except the one with index equal to index. When and object is deactivated, it becomes invisible and completely inactive, thus only one weapon will appear and obey the commands.
function SwitchGun(index : int)
{
for (var i=0;i < transform.childCount;i++)
{ // iterate through all childed weapons:
if (i == index) // if it's the selected index, activate it:
transform.GetChild(i).gameObject.SetActive(true);
else // if it's any other index, deactivate it:
transform.GetChild(i).gameObject.SetActive(false);
}
}
Download the First Person Tutorial Completed and you will see the character with its two weapon models childed to it.
EDITED: Function updated to Unity 4, which uses SetActive instead of the deprecated SetActiveRecursively. By the way, the FPS Tutorial is no longer available at Unity's site, but can be downloaded from http://visionquest3d.com/slam/FPS_TutorialsOld.zip
ohh... I see now. Thank you so much I can't wait to get back to coding! Unity is a great engine this my first time working in a 3d engine I've worked in a lot of 2d engines before but I wanted to take a step up and decided to take a good approach. Thanks for the help!
Your answer
Follow this Question
Related Questions
Weapon Switching 2 Answers
Weapon Switching 2 Answers
weapon sweep 1 Answer
Switching Between Cameras JavaScript 0 Answers
Problem With Weapon Firing Mechanism 1 Answer