How do you get a parent gameObject to read script from their children?

Hey

I’m new to Unity and am trying to get a parent gameObject to change a bool ONLY in their child gameObject since there will be multiple copies of the parent and child gameObjects. How would I do that?

Something like:

var childScript = gameObject.GetComponentInChildren<YourScript>();

Method#1: Declare your child explicitly in Editor

public class MyParent: MonoBehaviour{
  public MyScriptClass child; // drag child-GO/component into slot in editor

  void Update(){ // or any other method
     child.myBool = true;
  }
}

Method#2: Call GetComponent on parent

(...)


void Start(){  // if you will change it frequently set it on start
  myChild = gameObject.GetComponentInChildren<MyChildClass>();
}

void Update(){
  // if set in Start() Method
  myChild.myBool = true;
  
  // if set dynamically
  gameObject.GetComponentInChildren<MyChildClass>().myBool = true;
}

If you use method#1 you should save your GameObject as a Prefab, so every instance has it’s own child already set in the editor.

Method#2 requires that the parent has only ONE Component of that type in your Child GameObjects, otherwise you’ll just get the first found match returned.