- Home /
How to Change a Weapon with tag?
i have a problem, i want to make a switchweapon script. heres my working code that i am using:
var weapons: GameObject[];
private var curWeapon: int = 0; // now curWeapon is an int!
var shots: GameObject[];
private var curShot: int = 0;
function ChangeWeapon(weapon:int){
curWeapon = weapon;
for (var i = 0; i < weapons.length; i++){
weapons[i].SetActiveRecursively(i == weapon);
}
}
function ChangeShot(weapon:int){
curShot = weapon;
for (var i = 0; i < shots.length; i++){
shots[i].SetActiveRecursively(i == weapon);
}
}
function Update(){
if (Input.GetKeyDown("1")){
ChangeWeapon(0);
ChangeShot(0);
}
if (Input.GetKeyDown("2")){
ChangeWeapon(1);
ChangeShot(1);
}
if (Input.GetKeyDown("3")){
ChangeWeapon(2);
ChangeShot(2);
}
}
but theres the problem: i want to switch a weapon by pressing "E" when colliding with a weapon in the world.
help please :/
Answer by Xerosigma · Jun 21, 2012 at 07:14 PM
Why not use a trigger on the weapon collider? You can even set a range and if the player is pressing "E" within the range you can read the tag on the weapon you collided with and activate the weapon with the same tag on the player. Then of source you can disable the weapon on the floor.
function OnCollisionEnter (collision : Collision)
{
if(Input.GetKeyDown("E"))
{
// Get the Tag
WeaponTag = this.gameObject.tag;
// Enable the Weapon with the same tag on the player.
GameObject.FindGameObjectsWithTag(WeaponTag);
gameObject.SetActiveRecursively(true);
// Disable this one.
Destroy(this.gameObject);
}
}
Just an example but something close should work just fine. You might need to store the FindGameOjectWithTag results in an array because it could return more than one object. BUt I think you can handle it from hear! Hope it helps.
is there any possibility to communicate with the weaponindex script like GetComponent or Send$$anonymous$$essage?