[英]Unity 3D spawning a prefab from a List
我編寫了一個腳本,從我的Resources / ai文件夾中加載預制件,並循環最多執行五次,並生成一個隨機索引號。 它成功地將我的預制件作為GameObjects加載,並根據List的數量生成了隨機索引。
但是,由於在我編碼時Instatiate命令的確會返回錯誤,因此在將預制件生成到場景時遇到了麻煩。
我已經嘗試過通過list[index].name
甚至list[index].toString()
搶占預制件名稱的方法,但是它無法正常工作。 (注意: list
代表列表index
的變量,它只是在列表上獲取游戲對象的索引。這不是實際的代碼)。
如何使用列表將加載的GameObject預制生成到我的場景?
我當前的代碼:
public List<GameObject> ai;
public GameObject[] spawn;
int indexAI;
int indexSpawn;
private void Start()
{
var res = Resources.LoadAll<GameObject>("ai/");
foreach (GameObject obj in res)
{
ai.Add(obj);
}
for (int x=0; x<5; x++)
{
indexAI = UnityEngine.Random.Range(0,ai.Count);
indexSpawn = UnityEngine.Random.Range(0, spawn.Length);
string name = ai[indexAI].name;
Debug.Log(name);
//I am currently using this kind of format since this is what I know for now.
Instantiate(name,spawn[indexSpawn].transform.position,spawn[indexSpawn].transform.rotation);
}
謝謝!
您正在嘗試實例化字符串-您需要實例化AI列表中的gameobject。
Instantiate(ai[indexAI] ,spawn[indexSpawn].transform.position, spawn[indexSpawn].transform.rotation);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.