So, i made this code to switch weapons, and all i’m trying to do is get how much weapons the player has, so i know how to set the array, and then, put all weapons into the array, however, how do i get the objects with the “WeaponFire” component? So that i don’t need to set the array length before running the game, because i wont always have the same number of weapons.
BTW, this is not an FPS, nor a TPS, it is a car combat game.
Code:
#pragma strict
var currentWeapon = 0;
var Weapons : WeaponFire[];
function getSelectedWeapon() : WeaponFire
{
return Weapons[currentWeapon];
}
function Start()
{
if (currentWeapon >= Weapons.length) currentWeapon = Weapons.length-1;
for (var i=0; i<Weapons.length; i++)
DisableWeapon(Weapons[i]);
SelectWeapon(Weapons[currentWeapon]);
}
function Update () {
if (Input.GetKeyDown(KeyCode.PageUp))
SwitchWeapon(-1);
if (Input.GetKeyDown(KeyCode.PageDown))
SwitchWeapon(1);
}
function SwitchWeapon (iDir : int)
{
if (Weapons.length < 2) return;
// Desactivar coche previo
DisableWeapon(Weapons[currentWeapon]);
// Seleccionar coche nuevo
currentWeapon += Mathf.Sign(iDir);
if (currentWeapon < 0) currentWeapon = Weapons.length-1;
else if (currentWeapon >= Weapons.length) currentWeapon = 0;
SelectWeapon(Weapons[currentWeapon]);
}
// Desactivar el coche dado. No depende de variables globales.
function DisableWeapon(Weapon : WeaponFire)
{
Weapon.weaponSelected = false;
}
// Selecciona el coche dado. Lo activa y obtiene sus componentes.
function SelectWeapon(Weapon : WeaponFire)
{
Weapon.weaponSelected = true;
}
Uhm, that’s not it, i’m trying to create an array of all objects that contain a specific component, and not trying to get a component from one single object.
I ended up creating a very different setup for dynamic weapons, i simply created an empty and i attach all weapons to this empty, the script then counts how many child objects this empty has, and sets the array based on this. If anyone is having trouble with a similar issue, i’ll elave the code here:
#pragma strict
var currentWeapon = 0;
function Awake(){
SelectWeapon(0);
}
function Update(){
var maxWeapons : int = transform.childCount - 1;
if(Input.GetAxis("Mouse ScrollWheel") > 0){
if(currentWeapon + 1 <= maxWeapons){
currentWeapon++;
}
else{
currentWeapon = 0;
}
SelectWeapon(currentWeapon);
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0){
if(currentWeapon - 1 >= 0){
currentWeapon--;
}
else{
currentWeapon = maxWeapons;
}
SelectWeapon(currentWeapon);
}
if(currentWeapon == maxWeapons + 1){
currentWeapon = 0;
}
if(currentWeapon == -1){
currentWeapon = maxWeapons;
}
}
function SelectWeapon (index : int){
for (var i = 0; i < transform.childCount; i++){
if (i == index){
transform.GetChild(i).gameObject.GetComponent(WeaponFire).weaponSelected = true;
}
else{
transform.GetChild(i).gameObject.GetComponent(WeaponFire).weaponSelected = false;
}
}
}