- Home /
How to make different weapons deals different damage to enemy in C#
I'm making a shooter game where the player fires multiple weapons at the same time and the each weapons have different damage. For example: PeaShooter deal 3 damage per bullet while CarrotShooter deal 5 damage per bullet.
Here's my Enemy script if needed.
using UnityEngine;
using System.Collections;
public class EnemyStats : MonoBehaviour
{
public float enemyHealth = 30f;
private float currentHealth;
public bool enemyKilled = false;
public GameObject weapon;
private PeaShooter weaponDamage;
void Start()
{
weaponDamage = weapon.GetComponent<PeaShooter>();
}
void OnTriggerEnter(Collider other)
{
enemyHealth -= weaponDamage.ProjectileDamage;
currentHealth = enemyHealth;
if (enemyHealth <= 0f)
{
Destroy(gameObject);
}
}
}
How to make weapon other than PeaShooter deal it's own damage to the enemy? do i have to make another
weaponDamage = weapon.GetComponent<CarrotShooter>();
or is there other way / the correct way to do this?
Answer by Digital-Phantom · Jan 13, 2015 at 09:45 AM
You're going to need 2 sets of variables. One for your peashooter (you already got this) and another for your carrotshooter.
Then in your Ontrigger event tell it to deduct the damage from both weapons
whilst that might work, a better solution is to create a base class which all weapons can inherit from.
public class Weapon : $$anonymous$$onoBehavior
{
public float Health;
// add other common methods/variables/etc. here
}
public class PeaShooter : Weapon
{
// methods/variables/etc. specific to PeaShooter
}
public class CarrotShooter : Weapon
{
// methods/variables/etc. specific to CarrotShooter
}
then to get a reference to Health
you do the following:
var weapon = gameObject.GetComponent<Weapon>();
if (weapon != null)
{
// do something with weapon.Health
}
do some research on inheritance (and interfaces while you're at it) to get a better explanation of how they can help...
Your answer
![](https://koobas.hobune.stream/wayback/20220613180259im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Creating laser gun effect. 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Renderer on object disabled after level reload 1 Answer
FallDamage being given continously instead of just once 1 Answer