- Home /
How do I center a GameObject on its children?
I can do this using the editor but I'm trying to accomplish same using the API. Couldn't find anything the script reference. Any help would be highly appreciated. Thx.
Can you describe more clearly what you want to do? Do you actually want to set a parent gameobject position to the combined centre position of all its child gameobjects? I.$$anonymous$$ without moving the child objects at all, only the parent? at runtime?
Yes. What you described is exactly what I'm trying to accomplish. I want to set the parent gameobject to the combined center position of its child gameobjects...without moving any child objects and at runtime.
Answer by Horsman · Apr 19, 2010 at 11:10 AM
Sum the transform.position of all of the children, then, divide that by the count of the children. This is the centered position. Set each of the children's parent to null, then move the parent object to that position, and then set the children's parent to the parent object again.
Answer by m50 · Jan 10, 2010 at 05:30 AM
You can try removing the parent of the child, set the position of the main object to its child, then reparenting
Answer by era · Jan 24, 2010 at 12:20 PM
You could save the current combined position of the children in a var, then center the children to the parent (maybe using transform.localPosition or whatever suits your specific need), and then move the parent along with its children back to the saved previous position.
Since you'll be doing all this in one frame it'll be as realtime as it gets. I don't know how expensive this will actually be but it could be worth a shot. Hope this helps, good luck!
Answer by Joe Wreschnig · Jan 25, 2010 at 06:21 AM
If you are trying to move the parent relative to the children, it sounds like you may have your parent/child relationship backwards or sideways. What benefits is the parent/child relationship getting you besides a headache trying to solve this? If nothing, just get rid of it.
If the two things were siblings or the parent/child relationship was swapped, for example, you could just set the center of one to the center of the other.
Your answer
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
How to convert Unity games to Cardboard games for Android/iOS ? 1 Answer
NPC Class looking for help 1 Answer
how to get the prefab path of a game object in Game mode,not Editor mode 1 Answer
Edit GameObject.Variable 1 Answer