Thien
Thien

Reputation: 141

Unity: Detect Child Trigger inside Parent Script

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.

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

Upvotes: 1

Views: 3287

Answers (3)

Karol Borecki
Karol Borecki

Reputation: 36

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);

Upvotes: 0

Ahmad Reza
Ahmad Reza

Reputation: 68

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

Upvotes: 2

Valerij Dobler
Valerij Dobler

Reputation: 2764

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.

Upvotes: 0

Related Questions