Change parent of GameObject C#
Asked Answered
C

3

0

So lets say I got 2 cubes

Cube1 and Cube2

I wan't to assign Cube1 as the Parent of Cube2, can anyone give a code example of how that is done?

Convulsive answered 6/6, 2023 at 2:31 Comment(1)

But I think a missing audioSource gives a run-time error. And PlayOneShot is funny -- it's for "other" clips not attached to the audioSource. I use the OPs set-up (even 0.9 for sound level, empty clip in the audioSource slot) and it's fine. Now, if boom8 was empty, that won't give an error (you'd think it would, but I guess audio is used to getting nulls?)

Maiden
V
0

Sure,

Cube2.transform.parent=Cube1.transform

Verecund answered 21/3 at 14:17 Comment(5)

I tried looping through and adding all my asteroid game objects to a parent game object and they all appeared on top of each other. Not sure why this is happening tho.

Sentience

have you tried to set the cube2 transform to a null first then add parent.

Bonucci

Awesome.. my big problem was solved by your code :)

Virgule

As this answer can be found on google: There is a SetParent method now. It keeps the local orientation. [ScriptReference/Transform.SetParent.][1] [1]: https://docs.unity3d.com/ScriptReference/Transform.SetParent.html

Gonick

I get the error "CS0103: The name `Cube1' does not exist in the current context" How do I find Cube1?

Daub
D
0
Disquieting answered 8/7, 2018 at 3:58 Comment(0)
C
0

parent = gameobject keeps the worldposition of the child while SetParent allows you the choice between world position or changing the position to be relative to the parent.

'cube2.transform.SetParent(cube1.transform, true);

'cube2.transform.SetParent(cube1.transform, false);

'cube2.transform.parent = cube1.transform;

You can see a demonstration of how these will all parent the object but have different results on the position here https://www.monkeykidgc.com/2020/12/tips-and-tricks-unity-set-parent.html

Chilon answered 30/12, 2020 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.