Arthur friednman
Arthur friednman

Reputation: 41

Spawn prefabs as childs of a game object in unity

I have a spawner game object which spawns 2 different prefabs. 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):

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

Upvotes: 1

Views: 4894

Answers (1)

Alex Myers
Alex Myers

Reputation: 7195

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(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.

Note: As Draco18s mentioned, it is more efficient to overload Instantiate with the parent directly, as seen below:

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

Upvotes: 3

Related Questions