将预制件保存到阵列

时间:2015-01-29 09:59:50

标签: arrays unity3d unityscript gameobject

在我的游戏中,玩家可以从菜单中选择单位,稍后将在各种场景中使用(放置)。

为此,我想通过代码将单位预制件保存在静态数组中 然后我想访问这些预制件,以显示在附加脚本中声明的一些变量(如名称,电源和缩略图纹理)以在UI上显示。后来,我想将它们实例化为场景。

到目前为止,我无法将这些预制件保存到阵列中。

我的代码:

//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());

从最后一行,我收到此错误:

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

那么,我的错误在哪里?我忘记了什么或者说错了,或者我的方法在这里是无效的(即,预制件不能以这种方式保存/访问;另一种类型的列表可以更好地适应这项任务)。

1 个答案:

答案 0 :(得分:0)

您声明了数组没有类型。您可以将数组声明为GameObject的列表,也可以在提取元素时强制转换元素。

类型转换示例:

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());

使用通用列表的示例:

// 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());
相关问题