M
M
Mikhail Moor2017-05-05 11:55:45
Unity
Mikhail Moor, 2017-05-05 11:55:45

How to assign a parent in Unity?

There is a platform, a block is randomly created according to the script, I want the block to be created as a child object of the platform. How to do it?
Z, Y. If I find an answer on the Internet, I will write.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daniil Basmanov, 2017-05-05
@pasitiv

You can change the parent of a transform by calling Transform.SetParent or by directly replacing Transform.parent . In addition, in the latest versions of the unit, a new version of Instantiate has appeared , which allows you to specify the parent when creating an object.

using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    public Transform prefab;
    public Transform parent;

    private void Start()
    {
        // Создаём новый объект из префаба
        var child = Instantiate(prefab);
        // Присваиваем родителя
        child.SetParent(parent);
        // Либо так
        child.parent = parent;

        // Либо сразу в одну строчку
        var child = Instantiate(prefab, parent);
    }
}

When replying to your comment, check to whom you are trying to parent, a prefab or a new object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question