繁体   English   中英

Unity 3D从列表中生成预制件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM