OnCollisionEnter the Enemy Detect Collision but health damage not working but on OnTriggerEnter the health is reducing on punch but collision is not detecting

I have this script on the sphere (shown in Image 1) which is attached on the hand of Player to detect collision with enemy for a damage health.

public class HealthTrigger : MonoBehaviour
{
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == “Enemy”)
{
//gameObject.GetComponent();
HealthBar.health -= 10f;
}
}
}
146185-2.jpg

And I put this script on the HealthBar of Enemy Shown in Picture 2

public Image Health_Bar;
public float MaxHealth;
public static float health;
public GameObject enemy;
void Start()
{
Health_Bar = GetComponent();
health = MaxHealth;
}

// Update is called once per frame
void Update()
{
    Health_Bar.fillAmount = health / MaxHealth; 
    if(health <= 0)
    {
        Destroy(enemy);
    }
}

'I think it’s because of that you made ‘health’ in ‘Health_Bar’ static change it to a public variable and make sure that you UNCHECKED is trigger in collider of gameObject that contains Health_Bar and it will work just fine.


you can easily get enemy ‘Health_Bar’ in a list and set it on Start to improve performance and avoid form static variable.