- Home /
Weapon switching using array
Okay, i currently have 2 guns(ak47, 9mm) attached to the first person controller. They have animations. Show, hide,reload,etc..
Now, i can basically get them to switch by following the fps tutorial. However, i want to be able to use an array so later on i can manage the weapons better(pick up and drop weapons) and not switch a weapon currently equipped.
So switching the weapon like this works perfectly without the array.
transform.GetChild(i).gameObject.SetActiveRecursively(false);
weapons[i].gameObject.SetActiveRecursively(true);
However, when i use an array they wont switch and both guns show on play. Something that doesnt happen using transform.
I did assign both guns in the inspection for the array so they should contain the gun objects.
var weapons : GameObject[];
var selectedWeapon : int;
var handgunHide : Animation;
var handgunShow : Animation;
var AK47Hide : Animation;
var AK47Show : Animation;
function Start () {
SelectWeapon(0);
}
function Update () {
if(Input.GetKeyDown("1"))
{
SelectWeapon(0);
selectedWeapon = 0;
//handgunHide.animation.Play("Hide");
//AK47Show.animation.Play("Show");
}
else if(Input.GetKeyDown("2"))
{
SelectWeapon(1);
selectedWeapon = 1;
//handgunShow.animation.Play("Show");
//AK47Hide.animation.Play("Hide");
}
}
function SelectWeapon(index : int)
{
for(var i =0; i < weapons.Length; i++)
//transform.childCount; i++)
{
if(i == index)
{
weapons[i].gameObject.SetActiveRecursively(false);
//transform.GetChild(i).gameObject.SetActiveRecursively(true);
}
else{
weapons[i].gameObject.SetActiveRecursively(true);
//transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
}
I also tried to no avail
weapons[i].SetActiveRecursively(true);
if i dont use the array it works perfectly but if i do it wont work and both guns show. What could i do? I am perfectly fine using C# also.
Answer by fafase · Aug 25, 2012 at 12:04 AM
You could try:
function SelectWeapon(index : int){
for(var obj:GameObject in weapons)obj.SetActiveRecursively(false);
weapons[index].SetActiveRecursively(true);
}
Put them all off and only put back on the chosen one.
I tried it but both guns show on play and no switching. Thanks though.
It could be something related somewhere else. $$anonymous$$aybe in the weapon scripts
I got it working. Wheni added the guns to the array i was adding the prefabs from the project not from hierarchy.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
FPS gun animation problems 0 Answers
Fps Aiming Script help 2 Answers
FPS Weapon inventory script help 0 Answers