How to single out specific colliders from another object

Both the player and enemies have colliders for their bodies and for their attacks. I only want damage to be done when the enemy’s attack collider intercepts the players body collider or vice versa. However, I don’t know how to phrase the script in a way so that this is doable. Everything I’ve tried either results in repeated attacks having absolutely no impact on health or the player being injured when the enemy stands next to a couch.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DetectHit : MonoBehaviour {

    public Collider self;
    public Collider attack;
    public Collider target;
    public Slider healthbar;

    void OnTriggerEnter(Collider other)
    {
        if (other.gameObject != target) return;

        healthbar.value -= 20;
    }

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		
	}
}

The method I use to do it is easily is to create separated game objects in the editor for each collider you want to do a specific behaviour.

For example you have a player with a collider on his head, and a collider on his body, and if your enemy touch the head or the body it does two different things.

In my hierarchy window, my player will look like this :

96327-player-body.png

Player

  • Body (with a collider on it)
  • Head (with a collider on it)

Then you have several possibilities :

either your script with OnTriggerEnter function is on the enemy script, then you can use different tags on the player Body and Head to help you check which collider do you collide

or

your script with OnTriggerEnter function is on the player, and you can make two scripts, one on the player body to say what to execute when he collides the enemy and the other on the player head.