- Home /
Why is there no gameObject.parent?
Is there any reason for this?...
It seems sort of confusing that the Transform component deals with hierarchy (parent, childCount, DetachChildren, etc), when it mostly deals with location/rotation/scale, and is a part of the gameObject (which is a container for components and child objects)
I know you can just do gameObject.transform.parent... but that can get annoying when you are storing variables and keeping track of objects and constantly have to switch between gameobject and transform references...
Does anyone know the reason for this? or at least why there is no built-in inherited version to make gameObject.parent work?
This is a discussion question and should probably be asked in the forums rather than here. But, I would imagine it has to do with Unity's component based philosophy. A game object is nothing more than a container - all functionality belongs in the components. That's just a guess though.
To hopefully help why Transform deals with hierarchy and location &c:
Location, rotation, and scale are handled with matrices. A matrix is most efficiently created for child objects by "adding" it to the parent object. So a transform would say "draw me, then my children", and pass its matrix along, saving lots of time.
A GameObject, however, has no use for matrices. Since Transform already handles them and all GameObjects must have Transforms, it's redundant to have it in both places and could lead to a situation where a change is made in one place and not the other, causing hard-to-find bugs.
Thanks Loius, That helps explain things. How do I mark your comment as the correct answer?
Answer by zombience · Oct 23, 2013 at 08:27 PM
That's a design decision unity made.
If you really want to have that functionality, here's a class that will help you:
public static class ParentFinder
{
public static Transform parent(this GameObject obj)
{
return obj.transform.parent;
}
}
include the file ParentFinder.cs in any project you make, and now all gameObjects will have an accessible method called "parent" which will return the gameobject's transform's parent.
If you're going to be doing a lot of this per frame (like flocking hundreds of objects or something), you'll want to create a direct reference to the transform and the transform's parent.
This is called an extension method, in case the OP wants to read up on them.
Thanks, that method may be useful. I know there are many options for work-a-rounds, I was more curious on the design decisions by Unity... I guess this should have been posted in a discussion.