using UnityEngine;
using System.Collections;
public class PlayerWeapons : MonoBehaviour
{
public GameObject[] Weapon;
private int nextGun;
void Start()
{
// Select the first weapon
SelectWeapon(0);
}
void Update()
{
nextGun = Weapon;
if (Input.GetButton("Forward"))
{
SelectWeapon(nextGun + 1);
}
else if (Input.GetButton("Back"))
{
SelectWeapon(nextGun - 1);
}
}
void SelectWeapon( int index )
{
for (int i=0;i<transform.childCount;i++)
{
// Activate the selected weapon
if (i == index)
transform.GetChild(i).gameObject.SetActiveRecursively(true);
// Deactivate all other weapons
else
transform.GetChild(i).gameObject.SetActiveRecursively(false);
}
}
}
This should work:
using UnityEngine;
public class PlayerWeapons : MonoBehaviour
{
public GameObject[] Weapon;
private int currentWeaponIndex;
private void Start()
{
// Select the first weapon
SelectWeapon(0);
}
private void Update()
{
if (Input.GetButton("Forward"))
{
SelectWeapon(currentWeaponIndex + 1);
}
else if (Input.GetButton("Back"))
{
SelectWeapon(currentWeaponIndex - 1);
}
}
private void SelectWeapon(int index)
{
currentWeaponIndex = index;
// Make sure the index is within the range, and loop around if needed
if (currentWeaponIndex >= Weapon.Length)
currentWeaponIndex = 0;
if (currentWeaponIndex < 0)
currentWeaponIndex = Weapon.Length - 1;
for (int i = 0; i < Weapon.Length; i++)
{
// Activate the selected weapon
if (i == currentWeaponIndex)
Weapon*.gameObject.SetActive(true);*
// Deactivate all other weapons
else
Weapon*.gameObject.SetActive(false);*
}
}
}