Thursday, February 14, 2019

unity - Accesing child GameObjects of GameObject


I have already tried really much with all "GetChildren" and similar functions, but I haven't found out how to do it yet.


I have a GameObject named "koffer". I have added several other GameObjects as children to it.


I have added a script to "koffer" in which I try to retrieve the children. In this script I have stated this line:


    string sThis = this.name; //just for testing. "sThis" becomes "koffer", so it looks perfectly fine.
foreach (GameObject g in this.GetComponentsInChildren()) // doesn't retrieve anything. So obviously I'm not doing it correctly.

However this doesn't retrieve anything. Is this not the correct function for such a case?



Is there any built-in function to retrieve theses game obects?


I have found several custom made functions from some years ago, and I don't know if they are still needed or if Unity has integrated some functions for that.


What really bothers me is that there are so many custom-made functions that deal with "Transform" instead of "GameObject". Why would somebody need Transform instead of GameObject?


Thank you.



Answer



GameObjects do not have children per-se. When we talk about children to a GameObject we are actually referring to the children of the Transform component (that all GameObjects have). This means that you have to use the Transform component to access the children:


void Start() {
// All GameObjects have a transform component built-in
foreach(Transform child in this.transform) {
GameObject obj = child.gameObject;


// Do things with obj
}
}



The reason you can't use GetComponentsInChildren() to get the children is simply because that is not the functionality of that function. That function (like the name says) is used to get components from children (not the children themselves). For example (taken from Unity documentation):


void Start()
{
var hingeJoints = GetComponentsInChildren();

foreach (HingeJoint joint in hingeJoints)
joint.useSpring = false;
}

However I guess you can technically use this function to get all children:


void Start()
{
// This only works because GameObjects always have the Transform component,
// and there can only be 1 transform component per GameObject
var transforms = GetComponentsInChildren();

foreach (Transform transform in transforms) {
GameObject obj = transform.gameObject;

// Do something with obj
}
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...