I have a construct in my game that consists of a group of GameObjects like this:
Ship (Convex Mesh Collider / Rigid Body)
Shield Parent
Shield Emitter Element (Box Colliders)
... (Multiple Emitters)
The Ship and the Shield Emitter Elements both make use of a script component that is designed to handle collisions and track damage to the GameObject they are attached to.
The problem is that when something collides with the ShieldEmitterElement, the collision event gets called on Ship instead and I have no idea why. I’ve checked the bounds of the colliders for both items, and the Ship collider is definitely NOT extending out past the Shield Emitter Element, but it is definitively calling the script on the Ship, and the damage is being applied there.
This is the method in question:
public virtual void OnCollisionEnter(Collision collision) {
if (collision.gameObject.tag == "Dust") {
return;
}
DamagePacket Damage = new DamagePacket();
if (collision.gameObject.tag == "WeaponProjectile") {
DamageSource projectile = collision.gameObject.GetComponent<DamageSource>();
if (projectile.OriginShip == gameObject) {
return;
}
Damage = projectile.CalculateDamage();
Instantiate(projectile.impactParticles, collision.transform.position, Quaternion.Inverse(collision.transform.rotation));
Destroy(collision.gameObject);
} else {
if (collision.gameObject.GetComponent<Destructable>() != null) {
//Rigidbody otherRB = collision.rigidbody;
Damage = collision.gameObject.GetComponent<Destructable>().CollisionDamage(RigidBody.mass, collision.relativeVelocity.magnitude);
}
}
TakeDamage(Damage);
}
You’re most likely running into compound colliders, as you stated, if your parent object has a rigidbody. There are a couple ways to resolve it, including careful use of kinematic rigidbodies for individual child colliders, but in your case the most straightforward solution would be to use
collision.collider instead of collision.gameObject.
unlike the game object and transform references, which return the parent rigidbody object or transform, the collider property returns the immediate collider hit. You can use this to navigate your components in the same way you are using gameObject currently.
I’ve had the same issue couple days ago - had some Spikesas children of rigidbody. This script attached to parent worked. Just modify it to your needs
using UnityEngine;
using System.Collections;
public class ObstacleCollisionDetector : MonoBehaviour {
void OnCollisionEnter(Collision coll)
{
foreach (var contact in coll.contacts)
{
if (contact.thisCollider.GetComponent<Spike>() != null && contact.otherCollider.CompareTag("Player"))
EventsManager.Instance.InvokeCrashEvent();
}
}
}