How to link string to GameObject/Prefab, to load from?

Second time I am asking this question, first time no reaction so I tried to make it more clear.

So… I have this script(s) which creates a sort of shop, which you buy vehicle/parts from. When you walk up to the Object and click, a GUI opens up with turrets and such parts in it. Its only two turrets for now created 5 times at random when you start it up with icons and details. So now I need to link the string of each object(turrets in this case)to the Prefab in the Resources folder.

How to do that? Here is the code(s) for where the icons and names for the turrets get added into the UI.

// This is where the turrets get their names and cameos from.

private static TurretClass CreateTurCams(){



TurretClass turretClass = new TurretClass();

string[] turretNames = new string[2];
turretNames[0] = "gc40turret"; 
turretNames[1] = "gc120turret"; 

turretClass.Name = turretNames[Random.Range(0, turretNames.Length)];

turretClass.Cameo = (Texture2D)Resources.Load(TURRET_CAMEO_PATH + turretClass.Name);

return turretClass;



}

//This is where it gets added into the list for the GUI.

private void PopTurrets(int x){
 for(int cnt = 0; cnt < x; cnt++){

 baseList.Add(VehicleConstructor.CreateTurretCameos());

}


}

So yeah basically, I need to get those two turrets in the GUI of the shop linked to the actual Prefab it is meant for so I can load it into the game and instantiate.

I tried many ways but I end up making a big mess.

Please help me… Thanks.

If I understand correctly, you want to tie turret names (like gc40turret, gc120turret) to some prefabs in your Resources dir (eg. Turret40, Turret120). If yes, then you can do it the following ways:

  1. Make the turrent names the same as prefab names, and then load them using Resources.Load (just like you do for texture).

  2. Make mappings between names and prefabs using Dictionary class, initialize it in the Awake method, and use when accessing prefab:

    private Dictionary<string, GameObject> _dicTurretPrefabsByName = null;

    void Awake()
    {
    _dicTurretPrefabsByName = new Dictionary<string, GameObject>(); // ← UPDATE!!!
    _dicTurretPrefabsByName.Add(“gc40turret”, (GameObject)Resources.Load(“Turret40”));
    _dicTurretPrefabsByName.Add(“gc120turret”, (GameObject)Resources.Load(“Turret120”));
    }

    public void CreateTurret(string name)
    {
    var prefab = _dicTurretPrefabsByName[name];
    Instantiate(prefab);
    }