- Home /
Child calling parent's OnTriggerEnter when no Rigidbody is attached to child
I have a parent child relationship with a Player (the parent) and a Shield (the child). This was done so that when I instantiate the shield, it follows the Player as he moves.
The Player has a Kinematic Rigidbody attached, and the Asteroids that can collide with the Player or the Shield also have Kinematic Rigidbodies attached. The Shield does not have a Rigidbody attached. All of the above are marked in their Collider components as 'Is Trigger'.
In the above scenario, if a Player turns on their shield and an Asteroid hits it, the Player's OnTriggerEnter function is called, rather than the Shield's. Visually, the Asteroid is clearly being destroyed on contact with the Shield.
The desired behavior is for the Shield's OnTriggerEnter function to be called when it collides with an Asteroid, not the Player's. This happens in two scenarios. The first is if the Shield has a Rigidbody attached. The second is if a parent-child relationship isn't created between the Shield and the Player.
From reading this http://unity3d.com/support/documentation/Components/class-MeshCollider.html it seems like I have a Static Trigger Collider (the Shield) colliding with a Kinematic Rigidbody Trigger Collider (the Asteroid) which should send a message (and it is). The problem is that the message is being sent to the parent (the Player), rather than the Shield. I find this odd, since simply attaching a RigidBody to the Shield solves the problem.
I've pasted the code that establishes the parent-child relationship, and the OnTriggerEvent functions. Any help is appreciated.
// Player activates shield when he presses E.
if (Input.GetKeyDown(KeyCode.E) && !shieldActivated)
{
shieldActivated = true;
Transform shieldTransform = Instantiate(shield, transform.position, transform.rotation) as Transform;
shieldTransform.parent = transform;
Shield shieldScript = shieldTransform.GetComponent<Shield>();
shieldScript.Deactivated += new EventHandler(DeactivateShield);
}
// Player's OnTriggerEnter
void OnTriggerEnter(Collider other)
{
if (System.String.Compare(other.tag, "Asteroid") == 0)
{
Lives -= 1;
if (Crashed != null)
{
Crashed(this, EventArgs.Empty);
}
}
}
// Shield's OnTriggerEnter
void OnTriggerEnter(Collider other)
{
if (other.tag.Equals("Asteroid"))
{
hitsLeft -= 1;
if (hitsLeft <= 0)
{
if (Deactivated != null)
{
Deactivated(this, EventArgs.Empty);
}
Destroy(gameObject);
}
}
}
Answer by personWithQuestion · Dec 28, 2011 at 03:45 PM
Finally found this thread which answered my question. Apparently this is just how the engine works. I ended up removing the Rigidbody from the Player since it wasn't necessary. http://forum.unity3d.com/threads/36462-onCollisionEnter-does-not-work-on-a-child-colider