Access a GameObject through it's tag, using a string.

In a weapon pickup script i have, The script i have should find a gun, based upon it’s tag. In order to reuse this script instead of having 9 different ones, I added a string variable called gunname.

var gun : GameObject;
var myself : GameObject;
var player : GameObject;
var gunname : String;
var ammo : gunswitcher;

var isweapon1 : boolean = false;
var isweapon2 : boolean = false;
var isweapon3 : boolean = false;
var isweapon4 : boolean = false;
var isweapon5 : boolean = false;
var isweapon6 : boolean = false;
var isweapon7 : boolean = false;
var isweapon8 : boolean = false;
var isweapon9 : boolean = false;

var deadtime : float = 30;

var x : float = 0;
var y : float = 0.25;
var z : float = 0;

function OnTriggerEnter() {

gun.SetActive(true);
activate();
turnoff();

}

function turnoff() {

collider.enabled = false;
myself.SetActiveRecursively(false);

yield WaitForSeconds(deadtime);

collider.enabled = true;
myself.SetActiveRecursively(true);
}

function Start() {

InvokeRepeating("reset",0,0.25);

}


function reset()
{
    player = GameObject.FindWithTag("Player");
    ammo = player.GetComponent(gunswitcher);
	gun = GameObject.FindWithTag("gunname");
		
}

function Update() {

    transform.Rotate(x, y, z);

}


function activate() {
if(isweapon1 == true){
ammo.gunactive1 = true;
}
else if(isweapon2 == true){
ammo.gunactive2 = true;
}
else if(isweapon3 == true){
ammo.gunactive3 = true;
}
else if(isweapon4 == true){
ammo.gunactive4 = true;
}
else if(isweapon5 == true){
ammo.gunactive5 = true;
}
else if(isweapon6 == true){
ammo.gunactive6 = true;
}
else if(isweapon7 == true){
ammo.gunactive7 = true;
}
else if(isweapon8 == true){
ammo.gunactive8 = true;
}
else if(isweapon9 == true){
ammo.gunactive9 = true;
}


}

Everything else in the script except line 53 works. I’ve tried every permutation of the script I know, but nothing has worked. I need help with this.

Replace your:

gun = GameObject.FindWithTag("gunname");

To:

gun = GameObject.FindWithTag(gunname);

As already mentioned before, you’re actually searching for a GameObject with the tag ‘gunname’, whereas you want to use the variable called ‘gunname’. Also, when you run it - check in the inspector if the gunname variable is populating.