- Home /
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; } } }
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);
}
}
You need to format your code properly. If you're not willing to spend 2 $$anonymous$$utes to make it readable why would anyone help?
If you want OnCollisionEnter, OnCollisionExit, and OnCollisionStay to be called your GameObject must have a Rigidbody Component and a Collider Component (with Is Trigger UNCHE$$anonymous$$CED).
Answer by alireza97 · Sep 16, 2019 at 08:34 AM
'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.
Your answer
Follow this Question
Related Questions
Button Enabling/Disabling using Collision Triggers? 1 Answer
1 Button Alternating Between 2 onClick Functions 1 Answer
Coin Counter still not working after 5+ hours of frustrating changing code and moving stuff around 2 Answers
How to change a buttons color? 2 Answers
Unity HealthBar slider issues 0 Answers