Home > Mobile >  Unity - two human players, how to detect which player did most damage to AI enemy?
Unity - two human players, how to detect which player did most damage to AI enemy?

Time:12-04

I truly apologize for I have no code to offer here.

I am completely stumped, I’m still a coding noob and trying to run a simple exercise to test a game mechanic idea via prototype.

I’ll use a simple example:

  • 2 players vs. 2 AI enemies

  • both enemy ai have 400 points of health

  • both human players have guns that do 20 points of damage per trigger press.

  • both enemies are dead after a quick battle.

I want to reward the player who did the most damage to the enemies.

This is what I am trying to achieve: How do I go about detecting, which player, did the most damage to the enemy AI?

Any help would be appreciated, once I can grasp the concept of how to even go about doing this, I can then move forward on how to code it.

Thanks.

CodePudding user response:

The question is too general - there are a lot of ways to do this. Let's stick to OOP: let's make the "damage" object (script, class), which contains the following info: damage amount, player id. Wheh player hits trigger, lets assume, the bullet prefab is instantiated. It has a script (MonoBehaviour) on it, called "DamageContainer". When you instantiate a bullet, you also create your "damage" object, set correct values, and put it into bullet's "damage container". Then, when bullet collides with enemy, you get this info from bullet. Damage amount you use to reduce enemy's health. For counting damage, you need the counter itself. It can be a static class, a scriptable object, singleton, or something else. Let's use a static class, which is not the best practice, but simplest one. You need a simple static class, called "DamageCounter", and containing two public fields: Player1Damage and Player2Damage. When bullet collides with enemy, you need to add dealt damage to proper field of "DamageCounter", depending of damage.PlayerId field.

And don't forget to reset static class values on start of each battle.

  • Related