- Home /
The question is answered, right answer was accepted
Get Parent name of child
I found this child, and I need to know who their parents are, here's the script.
Transform[] allChildren = GetComponentsInChildren<Transform>();
foreach (Transform child in allChildren){
if (child.name == "4" && child.parent.name == "A") { // Here I need help with
var script1 = child.transform.gameObject.GetComponent<ScriptA>();
if (script1 == null) child.transform.gameObject.AddComponent("ScriptA");
}}
This is what I need help with child.parent.name. I tried different versions, adding transform, adding gameObject. I get Null Reference error.
Example: There are 3 parents with the name A, B, and C. Each have 9 children named 1 to 9. If child 1 is parented to A then add Script A, if child 5 is parented to C then add Script C etc. This will only be activated once, since its in the void start area.
I'm not sure what is going on, but a couple of things to note. child.parent.name should work as long as child.parent is not null. GetComponentsInChildren() will also return the component of the specified type in the game object used as the root. In this case, the game object this script is attached to. I'm guessing this script is on the parent. Put some Debug.Log() statements in your code:
Debug.Log(child.name+", "+child.parent);
If you see a null for 'child.parent', you know you've spotted a potential problem.
to "meat5000" transform.name get the child's name, anyways you don't need transform, child.name does fine, to find its name. I need parent not child.
Answer by rutter · Oct 22, 2013 at 08:31 PM
transform.parent
will give you the parent transform, or null if there is no parent (ie: it's at the top of the hierarchy).
When you call GetComponentsInChildren()
, that will also include the Transform of the script's own GameObject. If that GameObject is at the top of the hierarchy, it won't have a parent and you'll get a NullReferenceException.
So, with that in mind: what do you want to do with the top object? Do you want to ignore it, or should it get a ScriptA
attached as well?
To ignore it:
if (child.name == "4" && (child.parent != null && child.parent.name == "A"))
To include it:
if (child.name == "4" && (child.parent == null || child.parent.name == "A"))
In both of the above cases, a parent equal to null will "short-circuit" the logic evaluation, so that we never try to access its parent.
One last note, I notice you're trying to access child.transform.gameObject
. If child
is already a Transform, you probably don't need that extra reference.
thx, robert already solved it, samed answer as yours. I actually just made child.parent.name up and didn't even try it, I feel real stupid now, I had added transform and game object, in front, then back, then middle anyway I can think of, while writing this on questions, I made it short and simple and had no idea this would work.