简体   繁体   English

统一生成预制件作为游戏对象的子项

[英]Spawn prefabs as childs of a game object in unity

I have a spawner game object which spawns 2 different prefabs.我有一个 spawner 游戏对象,它生成 2 个不同的预制件。 I'm trying to make this spawned objects childs of the spawner game object but it does not work.我正在尝试使这个生成的对象成为生成器游戏对象的子对象,但它不起作用。

this is my try (this code is in the spawner game object):这是我的尝试(此代码在 spawner 游戏对象中):

void Update () {

    if (Time.time > nextSpawn)
    {
        whatToSpawn = Random.Range(1, 3);
        Debug.Log(whatToSpawn);

        switch(whatToSpawn) {
        case 1:
                Instantiate(cube, transform.position, Quaternion.identity);
                cube.transform.parent = transform;
                break;
        case 2:
            Instantiate(circle, transform.position, Quaternion.identity);
            circle.transform.parent = transform;
            break;
        }

        nextSpawn = Time.time + spawnRate;
    }
}

and this brings me this error:这给我带来了这个错误:

setting the parent of a transform which resides in a prefab is disabled

The problem is that you are trying to set the parents of the cube and circle prefabs, instead of the actual cube and circle objects you are instantiating.问题是您正在尝试设置立方体和圆形预制件的父级,而不是您正在实例化的实际立方体和圆形对象。 Replace your switch statement with the following:将您的 switch 语句替换为以下内容:

switch(whatToSpawn)
{
    case 1:
        GameObject myCube = (GameObject)Instantiate(cube, transform.position, Quaternion.identity);
        myCube.transform.parent = transform;
        break;
    case 2:
        GameObject myCircle = (GameObject)Instantiate(circle, transform.position, Quaternion.identity);
        myCircle.transform.parent = transform;
        break;
}

Casting the Instantiate function as a (GameObject) returns a reference to the object you just instantiated.Instantiate函数转换为(GameObject)返回对您刚刚实例化的对象的引用。

Note : As Draco18s mentioned, it is more efficient to overload Instantiate with the parent directly, as seen below:注意:正如 Draco18s 提到的,直接用父级重载Instantiate效率更高,如下所示:

switch(whatToSpawn)
{
    case 1:
        Instantiate(cube, transform.position, Quaternion.identity, transform);
        break;
    case 2:
        Instantiate(circle, transform.position, Quaternion.identity, transform);
        break;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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