Search code examples
arraysunity-game-engineunityscriptgameobject

Save prefabs to array


In my game, players shall be able to select units from a menu, which will later be used (placed) in various scenes.

For that, I want to save the unit prefabs in a static array through code.
I then want to access these prefabs, to display some of their variables declared in attached scripts (like name, power and a thumbnail texture) to display on the UI. Later, I want to instantiate them into the scenes.

So far, I fail to save these prefabs to the array.

My code:

//save to array
if (GUI.Button(Rect(h_center-30,v_center-30,50,50), "Ship A")){
    arr.Push (Resources.Load("Custom/Prefabs/Ship_Fighter") as GameObject);
}

//display on UI
GUI.Label (Rect (10, 10, 80, 20), arr[i].name.ToString());

From the last line, I get this error:

<i>" 'name' is not a member of 'Object'. "</i>

So, where is my mistake? Did I forget something or declare it wrong, or is my approach here invalid to begin with (i.e, prefabs can't be saved/accessed this way; another type of list would fit this task better).


Solution

  • You declared the array without type. You can either declare the array as a list of GameObjects or cast the elements when you extract them.

    Example of type casting:

    GUI.Label (Rect (10, 10, 80, 20), ((GameObject)arr[i]).name.ToString());    
    
    // which is equivalent to
    GameObject elem = (GameObject)arr[i];
    GUI.Label (Rect (10, 10, 80, 20), elem.name.ToString());
    

    Example of using a generic list:

    // Add this line at the top of your file for using Generic Lists
    using System.Collections.Generic;
    
    // Declare the list (you cannot add new elements to an array, so better use a List)
    static List<GameObject> list = new List<GameObject>();
    
    // In your method, add elements to the list and access them by looping the array
    foreach (GameObject elem in list) {
        GUI.Label (Rect (10, 10, 80, 20), elem.name.ToString());
    }
    
    // ... or accessing by index
    GameObject[] arr = list.ToArray;
    GUI.Label (Rect (10, 10, 80, 20), arr[0].name.ToString());