How to make the lifebar decrease

I am new to unity. There will be two objects, object1 and object2, everytime object2 touches object2 the lifebar will decrease for example 10%, i have a code here it is already decresig but only once,i want the life bar to decrease everytime the object1 touches object2. Whats wrong with the code/ Please help me.
Thank you.

using UnityEngine;
using System.Collections;

public class HEALTH : MonoBehaviour {
public float deduction=0.10f;
public UISlider RING;
public static float _playerHealth=100f;
public UISprite gameover;

//public UISlider slider;
void Start(){
	UpdateSubHealth();
}

public void OnTriggerEnter (Collider collider){
	if(collider.gameObject.name.ToString() == "Torus001"){
		_playerHealth-=deduction;
		Debug.Log("Hit by Colliders " + collider.gameObject);
		RING.sliderValue =0.10f;

		UpdateSubHealth();

	}
	Debug.Log("XHit by Colliders " + collider.gameObject.name.ToString());
	//UpdateSubHealth();

}

void UpdateSubHealth(){

}

}

Depending on your current setup I think the problem may be that before OnCollisionEnter can be called again, the two collider have to move apart first. If this is the case you can

  • either make sure that after the first hit the colliders are divided (not overlapping) before you want to apply damage again.

  • or you can use the OnCollisionStay() function, which will apply Damage while Objects are touching each other. To avoid apllying damage every Frame you can set the function up with a coroutine like this:

    bool touched;
    float timeToTouchAgain = 0.5f; // 0.5 seconds

     void OnCollisionStay(Collision collision)
     {
         if(collider.gameObject.name.ToString() == "Torus001")
         {
             if (!touched)
             {
                  StartCoroutine(MyTouch());
                  // Do you stuff, aplly damage
             }
         }
     
     }
     
     Ienumerator MyTouch()
     {
         touched = true;
         yield return new WaitForSeconds(timeToTouchAgain);
         touched = false;
     }
    

It should work. If you have any questions left, just ask :slight_smile: