0

私のゲームでは、プレイヤーはメニューからユニットを選択でき、後でさまざまなシーンで使用 (配置) されます。

そのために、ユニットのプレハブをコードで静的配列に保存したいと考えています。
次に、これらのプレハブにアクセスして、添付されたスクリプトで宣言された変数の一部 (名前、電源、サムネイル テクスチャなど) を表示して 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>

それで、私の間違いはどこですか?何かを忘れたのか、間違っていると宣言したのか、それともここでの私のアプローチはそもそも無効なのでしょうか (つまり、この方法でプレハブを保存/アクセスすることはできません。別のタイプのリストがこのタスクに適しています)。

4

1 に答える 1

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());
于 2015-01-29T10:11:40.347 に答える