- Home /
Callling a function in a child
Hello everyone. I'm new to unity and scripting (trying to learn C#) and have an easy question for you all. How can I call a function in a script that's attached to a gameObject's child? In the code below, I want to capture an object as a child on collision. I have an if statement in update that should call the function on the child, then unparent it. Any ideas?
public bool iWantToCallAFunctionThenDetachTheChild;
void Update() {
if (iWantToCallAFunctionThenDetachTheChild) {
foreach (Transform child in transform) {
MyCoolFunctionInChild();
}
transform.DetachChildren();
}
}
void OnTriggerEnter (Collider otherCollider) {
otherCollider.transform.parent = transform;
}
Comment
I'll write on the fly
NameOfScript Script;
void Start(){
Script = transform.parent.getComponent("NameOfScript") as NameOfScript
}
void Update(){
Script.YourCoolFunction();
transform.DetachChildren();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613120209im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
2D noise function to generate voxel circles 1 Answer
Code will not compare a child gameobjects tag to another 1 Answer
call a javascript function from c-sharp 2 Answers