Get Variable From String

var Prefabs : PrefabList = PrefabList();
class PrefabList
{
var Pistol : GameObject;
}

    function PickUpWeapon(WeaponName : String)
    {
       // need to get the variable Pistol inside Prefabs (Prefabs.Pistol)
       but get it from the string WeaponName, Example Prefabs.WeaponName
       so if WeaponName = Pistol then it would get Prefabs.Pistol, if
       WeaponName = Shotgun then it would get Prefabs.Shotgun, I am trying to
       do this so I don't have loads of if statements for every gun
       Prefabs.WeaponName.transform.position.y = 5;
    }

Using strings to define program behavior like that is kind of error prone and should be avoided, because strings are inherently free-form. This means you can write something like this elsewhere in your code:

private void Start()
{
    PickUpWeapon("Pastol");
}

And the compiler won’t catch the error, because “Pastol” is a valid string, even if it’s misspelled, and should’ve contained the word “Pistol”. That sort of stuff won’t cause an error until runtime, and then you’ll be left wondering why it didn’t instantiate a pistol prefab like it was supposed to.

To do this right, you need to practice type safety and define an enum to hold your weapons. Then pass that in as the parameter, and switch over it in the method. Like this:

public enum Weapons { Pistol, Shutgun, BaseballBat, Grenade} // As many as you want here. Define this outside the class definition.

Now you can define your method like this:

public void PickUpWeapon(Weapons weaponToPickUp)
{
    switch(weaponToPickUp)
    {
        case Weapons.Pistol:
            // Load Prefab.Pistol
            break;
        case Weapons.Shutgun:
            // Load Prefab.Shutgun
            break;
        case Weapons.BaseballBat:
            // Load Prefab.BaseballBat
            break;
        case Weapons.Grenade:
            // Load Prefab.Grenade
            break;
        default:
            break;
    }
}

And call it elsewhere like this:

    PickUpWeapon(Weapons.Pistol);

This is type safety. It raises a compile time error if you write something like this:

    PickUpWeapon(Weapons.Grinade);

Because the compiler knows, before the program runs, that “Grinade” is not a part of the enumerated values in Weapons.