I need to get the children in an object.
the closest I can find is…
GetComponentsInChildren(Transform);
but I need the object, not the component.
I need to get the children in an object.
the closest I can find is…
GetComponentsInChildren(Transform);
but I need the object, not the component.
You can access a transform’s gameObject via myTransform.gameObject.
No, I want to collect all the children.
like object.childrenInObject()
private List<GameObject> GetChildren(GameObject Parent)
{
List<GameObject> Children = new List<GameObject>();
Object[] AllObjects = GameObject.FindObjectsOfType(typeof(GameObject));
foreach (GameObject item in AllObjects)
{
if ((item.transform.parent == Parent.transform) (Children.Contains(item) == false))
{
Children.Add(item);
}
}
return Children;
}
something like that - sorry its kinda messy made the function on the spot…
Izitmee’s solutioin is still the correct one.
Transform[] childTransforms = GetComponentsInChildren<Transform>();
foreach (Transform childTran in childTransforms)
{
childTran.gameObject.... // this is the child GameObject
}
Oh ok,
Thanks.
I was getting errors originally suggesting my results were components, not transforms. Rehardless. Thanks!
There’s an example on this page.
http://unity3d.com/support/documentation/ScriptReference/Transform
This happens when you use a different overload of GetComponent that returns a Component that you need to cast yourself.
Another option, if you want, is to create an extension method that will give you back a list of GameObjects.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class HelperMethods
{
public static List<GameObject> GetChildGameObjects(this GameObject g)
{
List<GameObject> children = new List<GameObject>();
Transform[] childTransforms = g.GetComponentsInChildren<Transform>();
foreach (Transform childTran in childTransforms)
{
children.Add(childTran.gameObject);
}
return children;
}
}
And then just call it directly
List<GameObject> myChildren = gameObject.GetChildGameObjects();
You can also iterate through a transform directly:
foreach(Transform child in transform)
{
child.position = pos;
child.rotation = rot;
}
Cheers