Reputation: 629
My collider object has two child objects, there are camera and collider(is Triggered = true). I need to detect collision child collider and recognize all touched object by this child collider.
I think this is wrong code, but maybe not, at least just for some imagination:
CapsuleCollider legsTrigger;
void Update()
{
legsTrigger= GetComponentInChildren<CapsuleCollider>();
if(legsTrigger.contact...){
Debug.Log("This is : ");
Debug.Log(legsTrigger.gameObject.tag);
}
}
Upvotes: 1
Views: 3029
Reputation: 1076
You need to add a monobehaviour to your child. Otherwise you can't detect. If you want to check it from your parent gameobject, on this link there is a really nice solution for it by rsodre. I copied the codes from it and converted from 2D colliders to 3D.
Firstly, create a Bridge script between parent gameobject and childs
public class ColliderBridge : MonoBehaviour
{
ColliderListener _listener;
public void Initialize(ColliderListener l)
{
_listener l;
}
void OnCollisionEnter(Collision collision)
{
_listener.OnCollisionEnter(collision);
}
void OnTriggerEnter(Collider other)
{
_listener.OnTriggerEnter(other);
}
}
Then, add this ColliderBridge script to all childs, and then listen collision events from parent like this(Add ColliderListener script to parent gameobject).
public class ColliderListener : MonoBehaviour
{
void Awake()
{
// Check if Colider is in another GameObject
Collider collider = GetComponentInChildren<Collider>();
if (collider.gameObject != gameObject)
{
ColliderBridge cb = collider.gameObject.AddComponent<ColliderBridge>();
cb.Initialize(this);
}
}
public void OnCollisionEnter(Collision collision)
{
// Do your stuff here
}
public void OnTriggerEnter(Collider other)
{
// Do your stuff here
}
}
Upvotes: 3