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.

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.