Home > database >  Unity: Detect Child Trigger inside Parent Script
Unity: Detect Child Trigger inside Parent Script

Time:06-01

I am currently learning how to make games in Unity and I want to detect when a Child's collider is being triggered to apply the damage to the thing being hit. But I'm confused about how it works.

  • Does the Parent's OntriggerEnter detect the trigger event of the Child Object?
  • And how do I know the trigger comes from the Child and not the Parent?
  • And which Child's collider got triggered?

enter image description here

The Parent's collider is not triggered but the Child's collider is. Also the Child object doesn't have a rigidbody attach to it

CodePudding user response:

I don't have enough reputation to comment so I'm going to answer it. It's been answerd here as well I think : Collision Layer Matrix and Parent/Child object relationships.

If the child collision is not inside of parent collision you don't need to set IsTrigger = true for parent collision, just try different layers for you collisions.

Here is Unity documentation : https://docs.unity3d.com/Manual/LayerBasedCollision.html

CodePudding user response:

What you talk about is called self-collision. One way of handling this is to ignore certain colliders, take a look at the documentation here.

If I understood you correctly you have an GameObject hierarchy like so:

parentGO (contains player mesh and Capsule Collider 2D)
|-childGO (contains attack mesh and Mesh Collider 2D)

I'd attach to the childGO a script, which should register collisions on its polygon collider and notify the weapon script on the parentGO of the object being hit. The weapon can then deal the damage to the target.

CodePudding user response:

I know most likely You got your response, but It is also good to mention, that maybe You should think about separating these object and attaching them to new GameObject, that have a script holding both colliders - that might be more reliable and easy to read.

You can use Collider2D.IsTouching(Collider2D other);

Here is documentation for IsTouching

Or write custom script that uses the observer and notify the main GameObject that the collision occurred.

private Action _onGameObjectCollided;
private void OnTriggerEnter2D(Collider2D col){
    if(col.gameObject.CompareTag("TAG")
        _onGameObjectCollided?.Invoke();
}
public void AddOnColliderEnterObserver(Action observer)
{
    _onGameObjectCollided  = observer;
}

public void RemoveOnColliderEnterObserver(Action observer)
{
    _onGameObjectCollided -= observer;
}

And inside new GameObject:

collider.AddOnColliderEnterObserver(MethodToCallOnTriggerEntered);
  • Related