If enemy collides, lose health?

Updated on January 17, 2020 in [A] Unity Scripting
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
3 on January 17, 2020

Hi,

I’m new to Unity, I’ve been learning for about a month, and I’m making a platformer from tutorials from YouTube. However, I can’t seem to find tutorials, as the subject implies, if the enemy collides with the player, you lose health from the health bar.

I’m learning Unity for my coursework, and by learning, I mean looking up tutorials from YouTube.

I’ve already got a Health Bar, a player with scripts for platforming and that jazz, platforms, and a enemy. The Health Bar is from:

however I’ve not done the coding because I don’t think they’ve gotten a player or an enemy to test it out. I’ve got the platformer scripts from Brackeyes and the enemy AI too.

Any help would be greatly appreciated.

Thanks.

  • Liked by
Reply
1 on January 17, 2020

The Health Bar is from: https://youtu.be/Gtw7VyuMdDc 

on January 17, 2020

Changed the health bar to a slider. Still don’t know what to do… 

Show more replies
  • Liked by
Reply
Cancel
0 on January 17, 2020

What you probably want is to set the slider value in dependence of the player health.

sliderValue = playerHealth / maxPlayerHealth

The player health itself will be reduced if an enemy is inside the player trigger collider. To do it, just add a collider to the player and to the enemy. Give the GameObject, where the Collider is, a tag. For player “Player” and for enemy “Enemy”.

Next, go to the player script and add the following:

private void OnTriggerEnter(Collision other)
{
     if(other.tag == "Enemy")
     {
          DamagePlayer();
     }
}

The DamagePlayer() method is then done by you.

The OnTriggerEnter() method will be called, if another collider enters the player collider. To avoid that everything damages the player, there is an if sentence, which ask especially for a collider with an “Enemy” tag.

This should do your work.

  • Liked by
Reply
Cancel