- Home /
Get child tag from parent-child collision
I have a setup where I am building a maze recursively with square tiles. To try and limit the squares that a maze tile can be placed in, I've set up each tile with several children box colliders. These children are supposed to toggle a boolean in the parent script, but the children's tags don't affect the parent script, so the booleans are never toggled. Can I use the tag from the child in the parent's collision script?
The C# snippet is from the parent object. open[] is a bool array, countOpen is a counter
void onTriggerEnter (Collision other) {
if (this.tag.Equals("box4")) {
open[3] = false;
countOpen--;
}
if (this.tag.Equals("box3")) {
open[2] = false;
countOpen--;
}
if (this.tag.Equals("box2")) {
open[1] = false;
countOpen--;
}
if (this.tag.Equals("box1")) {
open[0] = false;
countOpen--;
}
}
Is there a method objects can invoke to get the tag from a child object during a trigger event? If you need more details I'd be happy to supply them when I return.
Answer by persijn · Dec 31, 2014 at 04:54 PM
void onTriggerEnter (Collision other) {
//this wil only find a single one
if (this.transform.find("childname/orgrandchild").gameObject.tag =="box4") {
open[3] = false;
countOpen--;
}
//this is maby better for you:
var gos = GameObject[];
gos = GameObject.FindGameObjectsWithTag("box");
foreach( GameObject taged in gos) {
if (taged.tranform.gameObject.parent == this) {
//You can name each box diffrent so your have a unique check
if (taged.tranform.gameobject.name == "nameofbox") {
//do something
}
}
}
}
Extra:
From the child element
if you just want to set variables its easier from the child:
void onTriggerEnter (Collision other) {
if (other != this.transform.gameObject.parent) return;
if (this.CompareTag("box4")) {
other.gameObject.open[1] == false
other.gameObject.countOpen--;
}
}
Right, but this doesn't work when the tag is on the child, not the parent. $$anonymous$$aybe I could use a trigger or collision event on the child object and send a message to the parent?
I updated my answer. I think the extra should be the easiest way.