Instantiate from Array C#

Hi Guys

I have my two different prefabs one for the price of my object and one for the name of the object and they correspond to each other by being in the same order so item 2 in my name array will be the second price listed in my price array.

now i want to add a third array to select the prefab that goes with the name ?
how would i do that and instantiate it into my scene ( just at 0;0;0)

here is my array script

// add itens to the itensArray

itensArray.Add("Potion");

itensArray.Add("Hi-Potion");

itensArray.Add("Ether");

itensArray.Add("Phoenix Down");

itensArray.Add("Mega-Potion");

itensArray.Add("Mega-Ether");

itensArray.Add("Elixir");

itensArray.Add("Speed-Tab");

itensArray.Add("Defense-Tab");

itensArray.Add("Power-Tab");

itensArray.Add("Mana-Tab");

itensArray.Add("Magic-Tab");

// add itens to the itensPriceArray

itensPriceArray.Add(25);

itensPriceArray.Add(50);

itensPriceArray.Add(70);

itensPriceArray.Add(50);

itensPriceArray.Add(500);

itensPriceArray.Add(700);

itensPriceArray.Add(700);

itensPriceArray.Add(1000);

itensPriceArray.Add(1000);

itensPriceArray.Add(1000);

itensPriceArray.Add(1000);

itensPriceArray.Add(1000);



	// add prefabs to item array
	
	itensPrefabArray.Add();

here is how i display all the items together

public void displayItens() {

    // Loop to display all the itensArray of the itensArray

    for(int cnt = 0; cnt < itensArray.Count; cnt++){

    

        //Buttom with Item Name

        if(GUI.Button (new Rect (0, 30 * (cnt), 230, 30), itensArray[cnt].ToString(), "box")){

            

            // Selects the item and it´s price

            selectedItem = itensArray[cnt].ToString();

            selectedItemPrice = (int)(itensPriceArray[cnt]);

            

            // resets the amount of itens selected

            amount = 1;

        }

    

        // Displays the Item Price

        GUI.Box (new Rect (230, 30 * (cnt), 50, 30), itensPriceArray[cnt].ToString());

        

        // calculates the total price

        totalPrice = amount * (int)(selectedItemPrice);

    } 

}

emphasized text

Ok so i decided to add the whole Store GUI script to help me explain.

@Neurological i convert the array into a string. but im not sure how i would do that with prefabs.

Your idea sounds great but i am not so handy with C# but im am trying to change over from Java to C# !

Could you please help me implement your idea into my script ? I understand the basics behind your script but not how to do it ?

using UnityEngine;

using System.Collections; 


 


public class StoreGUI : MonoBehaviour { 


#region DECLARED VARIABLES


    private Transform myTransform;              // NPC Transform


    private Transform playerTransform;          // Player Transform


    private float playerDistance;               // distance between Player and NPC


 


    public bool displayStore = true;            // show the store


    


    // define and create our GUI delegate


    private delegate void GUIMethod(); 


    private GUIMethod currentGUIMethod; 


    private Vector2 scrollPosition = Vector2.zero;


    


    // Array with the Itens


    public ArrayList itensArray = new ArrayList();


    public ArrayList itensPriceArray = new ArrayList();
		
		
	public ArrayList itensPrefabArray = new ArrayList();


 


    // Array with the Armor


    public ArrayList armorsArray = new ArrayList();


    public ArrayList armorsPriceArray = new ArrayList();
	
	
	public ArrayList armorsPrefabArray = new ArrayList();


    


    // Array with the Sword


    public ArrayList swordsArray = new ArrayList();


    public ArrayList swordsPriceArray = new ArrayList();


    public ArrayList swordPrefabArray = new ArrayList();


    private int amount = 1;                     //amount of itens to buy


    private int totalPrice;                     //total price of itens to buy


    private string selectedItem = "";           // selected item from the store


    private int selectedItemPrice;              // price of the selected item from the store


    


    private Color lerpedColor;                  //just a test


#endregion DECLARED VARIABLES


 


    // Use this for initialization


    void Start () { 


            


        GameObject go = GameObject.FindGameObjectWithTag("Player"); //find the GameObject w/ "Player" TAG


        playerTransform = go.transform;                             //and stores its Transform


    


        myTransform = transform;                // NPC transform;


                


        this.currentGUIMethod = itensMenu;      // start with the main menu GUI


 


        selectedItem = "";                      //sets the selected item to null


        


        addStuffToArrays();                     // fills the arrays with the Items


    }


 


    //Update is called Once per frame


    void Update(){


        


        //this is just a test


        lerpedColor = Color.Lerp(Color.green, Color.red, Time.time / 10);


        


        // stores the Distancie between the NPC and the player


        playerDistance = Vector3.Distance(myTransform.position, playerTransform.position);


        


        // if the playerDistance is bigger than 4, close the store


        if(playerDistance > 10){         


            displayStore = false;


        }


    }


    


    //Displays the store


    public void OnMouseUpAsButton() {       // When the NPC is clicked...


        if(playerDistance<10){               // and if playerDistance is lesser than 4...


            displayStore = true;            // then Displays the StoreGUI. 


        }


    }


 


#region OnGUI


    // Update is called once per frame 


    void OnGUI () {


    


        //Displays the store


        if(displayStore){


        


            //Text Item


            GUI.Label (new Rect (20, 40 , 230, 30), "Item");


            //Text Price


            GUI.Label (new Rect (250, 40, 40, 30), "Price");


        


            //button Exit


            if(GUI.Button (new Rect(20 + 100+100+100, 5, 100, 30), "Exit Store")){


                displayStore = false;


            }


    


            this.currentGUIMethod(); 


            


            // Area with selected item, amount, total price...


            GUILayout.BeginArea(new Rect( 20, 270, 400, 100));


            


            GUILayout.BeginVertical("box");


            


            GUILayout.BeginHorizontal("Label");


            //Text Item


            GUILayout.Box ("Selected Item", GUILayout.Width(110));


            //Text Amount


            GUILayout.Box ("Amount");


            //Text Total


            GUILayout.Box ("Total");


            GUILayout.EndHorizontal();


            


            


            GUILayout.BeginHorizontal("box");


 


            // Box with Item Name


            GUILayout.Box  (selectedItem.ToString(), GUILayout.Width(110));


 


            // Box with Amount


            GUILayout.Box  (" X " + amount.ToString(), GUILayout.Width(50));


            


            //Button Amount plus


            if(GUILayout.RepeatButton (" + ")){


                amount++;


            }


            //button Amount minus


            if(GUILayout.RepeatButton (" - ")){


                amount--;


            }


            //box Total Price


            GUI.color = lerpedColor;


            GUILayout.Box (totalPrice.ToString(), GUILayout.Width(80));


            


            //button Buy


            if(GUILayout.Button ("Buy")){


                addItemToInventory();


            }


            


            GUILayout.EndHorizontal();


            GUILayout.EndVertical();


            GUILayout.EndArea();


            


        }   //ends the displayStore IF


    }


#endregion OnGUI


    


    /*#---------------------- REGION MENUS----------------------------#*/


    


#region ITENS MENU  - called inside OnGUI   


    public void itensMenu() { 


        


        GUI.Box (new Rect (20, 5, 100, 30), "Itens Menu");  // Box with the Menu Title


        


        //Scroll Area with the Itens displayed Inside                                           // The scroll is dinamic generated by the size of the array


        scrollPosition = GUI.BeginScrollView(new Rect(20, 60, 300, 200), scrollPosition, new Rect(0, 0, 120, itensArray.Count * 30));


            displayItens();


        GUI.EndScrollView();


        


        if (GUI.Button (new Rect (20 + 100, 5, 100, 30), "Armors Menu")) {


            switchMenuForArmorsButton();                //Switch for Armors Menu


        } 


        


        if (GUI.Button (new Rect (20 + 100 + 100, 5, 100, 30), "Swords Menu")) {


            switchMenuForSwordsButton();                //Switch for Swords Menu


        } 


        


    } 


#endregion ITENS MENU


 


#region ARMORS MENU - called inside OnGUI


    private void armorsMenu(){


        


        GUI.Box (new Rect (20, 5, 100, 30), "Armors Menu");             // Box with the MenuTitle


        


        //Scroll Area with the Itens displayed Inside                                           // The scroll is dinamic generated by the size of the array


        scrollPosition = GUI.BeginScrollView(new Rect(20, 60, 300, 200), scrollPosition, new Rect(0, 0, 120, armorsArray.Count * 30));


            displayArmor();


        GUI.EndScrollView();


        


        if (GUI.Button (new Rect (20 + 100, 5, 100, 30), "Itens Menu")) {


            switchMenuForItensButton();                 // Switch for Itens Menu


        } 


        


        if (GUI.Button (new Rect (20 + 100 + 100, 5, 100, 30), "Sword Menu")) { 


            switchMenuForSwordsButton();                //Switch for Swords Menu


        } 


    }  


#endregion ARMOR MENU       


    


#region SWORDS MENU - called inside OnGUI


    private void swordsMenu(){


 


        GUI.Box (new Rect (20, 5, 100, 30), "Swords Menu");             // Box with the MenuTitle


        


        //Scroll Area with the Itens displayed Inside                                           // The scroll is dinamic generated by the size of the array


        scrollPosition = GUI.BeginScrollView(new Rect(20, 60, 300, 200), scrollPosition, new Rect(0, 0, 120, swordsArray.Count * 30));


            displaySword();


        GUI.EndScrollView();


        


        if (GUI.Button (new Rect (20 + 100, 5, 100, 30), "Itens Menu")) {       


            switchMenuForItensButton();                 // Switch for Itens Menu


        } 


        


 


        if (GUI.Button (new Rect (20 + 100 + 100, 5, 100, 30), "Armors Menu")) { 


            switchMenuForArmorsButton();                //Switch for Armors Menu


        } 


    }    


#endregion SWORD MENU   


 


#region SWITCH MENU BUTTOMs - called inside ITENS, ARMORS AND SWORDS MENUS()


    void switchMenuForItensButton(){


        this.currentGUIMethod = itensMenu;              // switch to Itens Menu


        amount = 1;                                     // resets the amount of itens selected


    }


 


    void switchMenuForArmorsButton(){


        this.currentGUIMethod = armorsMenu;             // switch to Armors Menu


        amount = 1;                                     // resets the amount of itens selected


    }


 


    void switchMenuForSwordsButton(){


        this.currentGUIMethod = swordsMenu;             // switch to Swords Menu


        amount = 1;                                     // resets the amount of itens selected


    }


#endregion  SWITCH MENU BUTTOMs


 


    /*#---------------------- END REGION MENUS-------------------------#*/


    


    /*#---------------------- REGION DISPLAY ITENS LOOPS----------------------------#*/


#region DISPLAY ITENS LOOP  - called inside ItensMenu()


        public void displayItens() {


                            


            // Loop to display all the itensArray of the itensArray


            for(int cnt = 0; cnt < itensArray.Count; cnt++){


            


                //Buttom with Item Name


                if(GUI.Button (new Rect (0, 30 * (cnt), 230, 30), itensArray[cnt].ToString(), "box")){


                    


                    // Selects the item and it´s price


                    selectedItem = itensArray[cnt].ToString();


                    selectedItemPrice = (int)(itensPriceArray[cnt]);


                    


                    // resets the amount of itens selected


                    amount = 1;


                }


            


                // Displays the Item Price


                GUI.Box (new Rect (230, 30 * (cnt), 50, 30), itensPriceArray[cnt].ToString());


                


                // calculates the total price


                totalPrice = amount * (int)(selectedItemPrice);


            } 


        }


#endregion DISPLAY ITENS LOOP


        


#region DISPLAY ARMORS LOOP - called inside ArmorsMenu()


        public void displayArmor() {


            


            // Loop to display all the itensArray of the array


            for(int cnt = 0; cnt < armorsArray.Count; cnt++){


 


                //Buttom with Armor Name


                if(GUI.Button (new Rect (0, 30 * (cnt), 230, 30), armorsArray[cnt].ToString(), "box")){


                    


                    // Selects the armor and it´s price


                    selectedItem = armorsArray[cnt].ToString();


                    selectedItemPrice = (int)(armorsPriceArray[cnt]);


                    


                    // resets the amount of itens selected


                    amount = 1;


                }


                


                // Displays the Item Price


                GUI.Box (new Rect (230, 30 * (cnt), 50, 30), armorsPriceArray[cnt].ToString());


                


                // calculates the total price


                totalPrice = amount * (int)(selectedItemPrice);


            } 


        }


#endregion DISPLAY ARMOR LOOP


 


#region DISPLAY SWORDS LOOP - called inside SwordsMenu()


        public void displaySword() {


            


            // Loop to display all the itensArray of the array


            for(int cnt = 0; cnt < swordsArray.Count; cnt++){


 


                //Buttom with Armor Name


                if(GUI.Button (new Rect (0, 30 * (cnt), 230, 30), swordsArray[cnt].ToString(), "box")){


                    


                    // Selects the armor and it´s price


                    selectedItem = swordsArray[cnt].ToString();


                    selectedItemPrice = (int)(swordsPriceArray[cnt]);
				
					


                    


                    // resets the amount of itens selected


                    amount = 1;


                }


                


                // Displays the Item Price


                GUI.Box (new Rect (230, 30 * (cnt), 50, 30), swordsPriceArray[cnt].ToString());


                


                // calculates the total price


                totalPrice = amount * (int)(selectedItemPrice);


            } 


        }


#endregion DISPLAY SWORD LOOP


 


    /*#---------------------- END REGION DISPLAY ITENS LOOPS------------------------#*/


 


 


 


#region ADD ITEM TO INVENTORY - called inside OnGUI - "buy" button  


    public void addItemToInventory(){           // Method for the buy buttom


        


        if(selectedItem != ""){                 //se selectedItem for diferente de null


            print("Bought Item!");


            // To Add Item X amount; - Use a loop   


            /* 


            for(int cnt = 0; cnt < amount; cnt++){


                addItemToInventory(selectedItem);


            }


            


            curGold - totalPrice;


            */


        }


    }


#endregion ADD ITEM TO INVENTORY


    


#region ADD STUFF TO ARRAYS - called inside Start()


    // Fills itensArrays, armorsArray, swordsArray, and PricesArray with the itens


    private void addStuffToArrays(){


    


    // add itens to the itensArray


        itensArray.Add("Potion");


        itensArray.Add("Hi-Potion");


        itensArray.Add("Ether");


        itensArray.Add("Phoenix Down");


        itensArray.Add("Mega-Potion");


        itensArray.Add("Mega-Ether");


        itensArray.Add("Elixir");


        itensArray.Add("Speed-Tab");


        itensArray.Add("Defense-Tab");


        itensArray.Add("Power-Tab");


        itensArray.Add("Mana-Tab");


        itensArray.Add("Magic-Tab");


            


    // add itens to the itensPriceArray     


        itensPriceArray.Add(25);


        itensPriceArray.Add(50);


        itensPriceArray.Add(70);


        itensPriceArray.Add(50);


        itensPriceArray.Add(500);


        itensPriceArray.Add(700);


        itensPriceArray.Add(700);


        itensPriceArray.Add(1000);


        itensPriceArray.Add(1000);


        itensPriceArray.Add(1000);


        itensPriceArray.Add(1000);


        itensPriceArray.Add(1000);


        

		// add prefabs to item array
		
		itensPrefabArray.Add(10);
		

    // add itens to the armorsArray


        armorsArray.Add("Leather Coat");


        armorsArray.Add("Gold Shield");


        armorsArray.Add("Platinum Armor");
		
		
		armorsArray.Add("Reda Chest Plate");

        


    // add prices to armorsPriceArray


        armorsPriceArray.Add(200);


        armorsPriceArray.Add(1000);


        armorsPriceArray.Add(2000);
		
		
		armorsPriceArray.Add(1000);
        


        


    // add itens to the swordsArray


        swordsArray.Add("Wood Sword");


        swordsArray.Add("Steel Sword");


        swordsArray.Add("Buster Sword");


        swordsArray.Add("Rainbow");


        swordsArray.Add("Onimusha Sword");


        swordsArray.Add("Sword Of Sparda");


        swordsArray.Add("Blade Of Chaos");  


        swordsArray.Add("Masamune");    


        


    // add prices to swordsPriceArray


        swordsPriceArray.Add(100);


        swordsPriceArray.Add(500);


        swordsPriceArray.Add(1000);


        swordsPriceArray.Add(25000);        


        swordsPriceArray.Add(30000);


        swordsPriceArray.Add(40000);


        swordsPriceArray.Add(50000);


        swordsPriceArray.Add(80000);


    }


#endregion ADD STUFF TO ARRAYS


}

Ok so for the prefab array, you can either do like someone above suggested by filling the array from the Resources folder, but you will have to it one by one as you have to specify the order in the array to match the others arrays. Alternatively you can just fill the array from unity in the Inspector where you got the shop script.

You can use a simple public GameObject prefabs; kind of array. Now to instatiate them I don’t know i you want to make a single button to buy the item and then instantiate and the logic you have to compare prices and all, but you can directly use the array index to instate it.

In your code I see you have the code to duplicate the buttons with all the item names and when you click the name the description appear. So I would suggest without changing your code too much you can add some integers to see what button was pressed, something like:

private int curItemSelected;
private int curArmorSelected;
etc…

So on the button code when you press it you just add this: curItemSelected = cnt;
This will make the integer change to the exact index of the item array you want to instantiate. Then on your “Buy” button or whatever you choose to instatiate the prefab you just need a simple function like:

void InstantiateItem () { 
	Instantiate(prefabs[curItemSelected], Vector3.zero, Quaternion.identity);
}

prefabs is just a test name for your prefab array, you can call it whatever you want, as you see inside the parenthesis there is curItemSelected that is used just as index for the right item to instatiate.

Vector3.zero and Quaternion.identity will instantiate the item at 0,0,0 like you requested, but you can easily change to instantiate whereever you want.

Hope I was clear enough, for anything just ask.

PS: I changed one of my comments back with the array example as I did a typo.