setparent unity что это

Transform.SetParent

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Parameters

parentThe parent Transform to use.
worldPositionStaysIf true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.

Description

Set the parent of the transform.

This method is the same as the parent property except that it is possible to make the Transform keep its local orientation rather than its global orientation. This is managed by setting the worldPositionStays parameter to false. When SetParent is called with only the single Transform argument the worldPositionStays argument is set to true.

Did you find this page useful? Please give it a rating:

Thanks for rating this page!

What kind of problem would you like to report?

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at

Thanks for letting us know! This page has been marked for review based on your feedback.

If you have time, you can provide more information to help us fix the problem faster.

You’ve told us this page needs code samples. If you’d like to help us further, you could provide a code sample, or tell us about what kind of code sample you’d like to see:

You’ve told us there are code samples on this page which don’t work. If you know how to fix it, or have something better we could use instead, please let us know:

You’ve told us there is information missing from this page. Please tell us more about what’s missing:

You’ve told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:

You’ve told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:

You’ve told us there is a spelling or grammar error on this page. Please tell us what’s wrong:

You’ve told us this page has a problem. Please tell us more about what’s wrong:

Thanks for helping to make the Unity documentation better!

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.

Copyright © 2018 Unity Technologies. Publication: 2017.3-002A. Built: 2018-04-04.

Источник

Tips and Tricks: Unity Set Parent

setparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что это

Tips and Tricks: Unity Set Parent

Introduction

In Unity setting the parent GameObject for items in your game is an important feature to understand. This can be used for picking up weapons, carrying items, or tethering two objects together. Child objects can appear to behave in strange ways if you do not understand their positioning and how it relates to the parent or game world you have created. In this Tips and Tricks will show you how to properly set the parent GameObject using the method SetParent in Unity.

Getting Started

Unity Documentation

In the Unity Documentation for SetParent we can find the implementation for the method. It is a method that is called on the Transform of a GameObject. Every object that you have placed in a scene has this component. Transform specifies where an object is in the scene, how it is rotated, and what the scale is from the object’s original size. Transform also contains a property for tracking a parent object.

Furthermore, the Transform.SetParent method can take two values. First, is the Transform of the parent. Second, a boolean to signify whether the GameObject should adjust to the parent’s transform, again that is position, rotation, and scale, or should it stay relative to the world, which we will elaborate on soon.

What is a Parent?

At this point, you may be wondering “what is a parent GameObject”. The easiest way to explain a parent is to think of it as a container or a box. If you move the box the things inside of it move, if you attach a water cannon to the box it can now shoot water, if you put a snake in the box you will get a plot about stealth operatives, and if you destroy the box everything inside of it is destroyed.

The Set Up

To begin, this demonstration has a fairly simple setup. We have a class named TTSetParent that contains two public fields, a boolean and a transform. Any GameObject with this script attached will set its parent with the provided data on Start. Here is the entire script.

In addition to the script, we have created four sprite assets of various shapes and colors. Then, we attached our script to the triangle and square sprite shapes and assigned the circle sprite shape to the parent field for each and left the Worldspace checkbox unchecked.

Triangle – with position set to (0, 2), to place slightly above center, and color set to red.

Square – Its position is set to the same as the triangle, so that they overlap, and the color set to black.

Hexagon – Set to position (0, 0) and color set to yellow. This will represent the center of our game world and will not change.

Unity SetParent

Now, we can run our demo in the editor. You will immediately notice that both the triangle and square move to the center of the screen and overlap the yellow hexagon. Select either the triangle or the square and observe the position coordinates in the inspector. They are still set to (0, 2). Do the same for the hexagon and you will notice that it is also still set to (0, 0), but how are these GameObjects occupying the same space?

In spite of these objects being visually in the same space in the scene, they are referencing different points of origin. For the triangle and square, which are now child objects of the circle, their world centers around the circle, while the hexagon centers around the world position of (0, 0).

Set Parent with World Position

To demonstrate how world position can impact your objects placement, select the triangle GameObject and click the check box for Worldspace. This will set our world space value to true. With that done, select play in the Unity editor to see what impact it will have.

This time, the triangle stayed where it was at while the square object moved to cover our hexagon in the center of the game world. Select the triangle object in the hierarchy and view the position in the inspector. Something different has happened, the Y coordinate shows 4.

Set Parent Rotation

To continue, we can further complicate things by adding rotation into the mix. Select the circle GameObject and change the Z rotation to 90. Hit play in the editor to see what impact this will have.

Set Parent Scale

Finally, we can take these same principles and apply them to the scale property. Set the circle X scale to 2.5 and click play in the Unity editor. We will now see that the square is stretched into a rectangle and while, again, maintaining the same values it was originally set to by becoming relative to the parent circle. The triangle however has reduced its scale to maintain its values in world space.

And now you are ready to parent GameObjects while making games in Unity. Thank you for stopping by. Stick around and check out more of our tutorials or posts like our piece on Tips and Tricks: Unity Instantiate Prefab as Child of GameObject. Also, leave a comment telling us what you liked or did not like about the tutorial. Was it easy to follow along? What do you want to learn next? As always check out some of our published apps below.

Источник

Русские Блоги

Unity 3D UI установить отношения родитель-потомок setParent pit

Напишите перед:

При выполнении проектов неизбежно возникает много пользовательского интерфейса, и динамическая загрузка пользовательского интерфейса является очень важной проблемой. Пользовательский интерфейс динамической загрузки должен учитывать отношения родитель-ребенок при настройке пользовательского интерфейса. Обычно мы будем использовать transform.setparent (transform), чтобы установить отношения родитель-потомок. Здесь все еще нет ничего плохого. Но пользовательский интерфейс должен учитывать второй параметр при настройке родительско-дочерних отношений. Для начинающих часто встречается, что пользовательский интерфейс загружается.После установки подобъектов пользовательский интерфейс отсутствует, но, очевидно, правильно перетащить непосредственно на уровень пользовательского интерфейса. Эта проблема связана со вторым параметром.

worldPositionStays, Так что это тоже вопрос, который нужно учитывать.

Анализ причины, по которой пользовательский интерфейс устанавливает родительский объект

При загрузке пользовательского интерфейса этот шаг загрузки фактически загружает экземпляр пользовательского интерфейса в корневой путь сцены, а затем устанавливает его в родительский объект. Этот процесс может быть выполнен вручную, сначала добавьте пользовательский интерфейс и перетащите его в корневой путь сцены, а затем перетащите его на родительский объект, эффект, отображаемый в это время, является конечным эффектом.

Причина: в процессе перетаскивания из корневого пути к родительскому объекту происходит преобразование координат. Смотрите ниже для конкретного анализа и решений.

setparent()

Здесь мы сначала проанализируем эту функцию. Эта функция имеет две перегрузки:

public void SetParent(Transform parent);

public void SetParent(Transform parent, bool worldPositionStays);

Определение второго параметра в API выглядит следующим образом:

worldPositionStaysIf true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.

Официальное объяснение: если это правда, то сохраните предыдущую позицию, величину поворота и значение масштабирования. Если это не так, положение, поворот и масштаб локальных координат сохраняются.

Может быть нелегко понять значение этого параметра напрямую, поэтому оглянемся назад.

Возникшие проблемы

Обычно, когда мы устанавливаем отношения родитель-потомок, мы надеемся, что после установки дочерний объект должен сохранить первоначальный вид. Если это изменится, это окажет серьезное влияние на взаимодействие игры. 3D-объекты относительно хороши. Если родительский объект не установлен в пользовательском интерфейсе, он будет серьезно деформирован.

Ниже приведен сравнительный тест воздействия этого параметра:

setparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что это

setparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что этоsetparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что это

Выберите квадрат как дочерний объект, чтобы увидеть изменения.

Сначала параметр верен.

setparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что это

Эффект остается прежним. Локальные значения координат сферы и квадрата:

setparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что этоsetparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что это

Можно видеть, что эффект гарантирует, что блок не изменяется со сменой сферы, но его локальное значение координаты изменилось, причем сфера является центром, но эффект остается прежним относительным положением.

setparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что это

Из этого эффекта видно, что значения поворота и масштабирования блока изменились, и они не сохраняются в исходной мировой системе координат. Локальные значения координат сферы и квадрата:

setparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что этоsetparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что это

Из параметров видно, что локальное значение квадрата гарантированно совпадает с предыдущим значением в глобальной системе координат.

Видно, что воздействие все еще относительно велико.

Для пользовательского интерфейса

Для пользовательского интерфейса, мы хотим сохранить эти позиционные отношения или нет? Ответ очевиден. Когда мы делаем предустановку пользовательского интерфейса, это делается под родительским объектом пользовательского интерфейса. Значение, сохраненное в предустановке, также является значением в локальной системе координат пользовательского интерфейса.

При первой загрузке в корневой путь сцены пользовательский интерфейс теперь заменяет значение предыдущей локальной системы координат глобальной системой координат.

Чтобы гарантировать то же самое, что и предыдущий пользовательский интерфейс, нам нужно перенести это позиционное отношение в родительский объект пользовательского интерфейса.

Так что это должно быть установлено в false.

Источник

Transform.SetParent

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please try again in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Parameters

parentThe parent Transform to use.
worldPositionStaysIf true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.

Description

Set the parent of the transform.

This method is the same as the parent property except that it is possible to make the Transform keep its local orientation rather than its global orientation. This is managed by setting the worldPositionStays parameter to false. When SetParent is called with only the single Transform argument the worldPositionStays argument is set to true.

Did you find this page useful? Please give it a rating:

Thanks for rating this page!

What kind of problem would you like to report?

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at

Thanks for letting us know! This page has been marked for review based on your feedback.

If you have time, you can provide more information to help us fix the problem faster.

You’ve told us this page needs code samples. If you’d like to help us further, you could provide a code sample, or tell us about what kind of code sample you’d like to see:

You’ve told us there are code samples on this page which don’t work. If you know how to fix it, or have something better we could use instead, please let us know:

You’ve told us there is information missing from this page. Please tell us more about what’s missing:

You’ve told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:

You’ve told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:

You’ve told us there is a spelling or grammar error on this page. Please tell us what’s wrong:

You’ve told us this page has a problem. Please tell us more about what’s wrong:

Thanks for helping to make the Unity documentation better!

Is something described here not working as you expect it to? It might be a Known Issue. Please check with the Issue Tracker at issuetracker.unity3d.com.

Copyright © 2018 Unity Technologies. Publication: 2018.1-002N. Built: 2018-12-04.

Источник

Transform.SetParent

Parámetros

parentEl Transform padre a utilizar.
worldPositionStaysIf true, the parent-relative position, scale and rotation are modified such that the object keeps the same world space position, rotation and scale as before.

Descripción

Configure el padre del transform.

This method is the same as the parent property except that it also lets the Transform keep its local orientation rather than its global orientation. This means for example, if the GameObject was previously next to its parent, setting worldPositionStays to false will move the GameObject to be positioned next to its new parent in the same way.

The default value of worldPositionStays argument is true.

The image below shows a child GameObject in its original position:

setparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что это

Here’s how it looks after calling SetParent with worldPositionStays set to true:

setparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что это

Here’s how it looks after calling SetParent with worldPositionStays set to false:

setparent unity что это. Смотреть фото setparent unity что это. Смотреть картинку setparent unity что это. Картинка про setparent unity что это. Фото setparent unity что это

Notice how the Child Sphere is in the same position but now relative to the New Parent Cube.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *