Collision Updating UI Slider only once.

I’m making a flat 2D fighting game, and I’m trying to update my player2Health slider when player 1 collides with player 2 (of course I don’t know if I am going this the right way, it’s my first game). Preface: Also spent about an hour or so researching, but maybe I didn’t search for the right thing.

For now I have the step working of where the slider updates OnCollisionEnter2D but it’s only firing once.

void OnCollisionEnter2D (Collision2D col) {

	
	if (col.gameObject.tag == "Player2")
	{
		GameHud.player2HealthUI.value = currentHealth - 10f;
		Debug.Log ("Colliding with player 2");
	}

}

Am I using this the wrong way? I thought to use OnTriggerEnter2D but then making my player gameobjects triggers make them fall through other colliders.

1 Answer

1

You should be doing this in order to ceep track of the currentHealth

void OnCollisionEnter2D (Collision2D col) {
    if (col.gameObject.tag == "Player2")
    {
        currentHealth-= 10;
        GameHud.player2HealthUI.value = currentHealth; 
        Debug.Log ("Colliding with player 2");
    }
}

Wow. Thanks so much and all it took was one line. I will keep this in mind when I have other objects (like special moves) or so. So for future reference, when I am updating a gameobject value, or meter, etc.. I should update the variable before changing the value, correct? (Not try and do both at the same time which is probably what I was doing) Just making sure I understand this right.