Multiple different bullet damages for multiple enemies
In my game, I currently have multiple types of bullets (that do different amounts of damage) and multiple enemies (that have different amounts of health). What's the best way to implement enemies taking damage from the bullets? I'm trying to make my code as clean as possible.
Currently the way I see it is for each enemy, have a long if/else statement checking the type of bullet that the enemy was struck by, and removing a certain amount of health based on that, but that seems messy and redundant because each bullet should do the same amount of damage to each enemy.
Ideally, I imagine each bullet checking in its onCollision whether the object it struck had the "Enemy" tag, and if so, call some method removeHealth(float damage) for example on that game object. However, each of my enemies are currently in a different script so I don't think I can blindly call a removeHealth method on the target.
Is there a better way to implement this? Thanks.
Answer by Ardaaytac · Sep 03, 2016 at 07:48 PM
You can use enum for these type of variables. For example,Imagine your Bullet script;
public enum BulletType
{
Missile,
BouncyBullet,
HeavyBullet
}
public BulletType bulletType;
and use that bulletType variable on your game manager or whatever you want to use.
Edit: If you want to use that OnCollisionEnter ;
void OnCollisionEnter(Collider col)
{
if(bulletType == BulletType.Missile && col.gameObject.tag == "Player")
Debug.Log("Missile succesfully hit the player");
}
void OnCollisionEnter(Collider col)
{
health = (bulletType == BulletType.$$anonymous$$issile && col.gameObject.tag == "Player" ? RemoveHealth (500) : bulletType == BulletType.BouncyBullet && col.gameObject.tag == "Player" ? RemoveHealth (250) : bulletType == BulletType.HeavyBullet && col.gameObject.tag == "Player" ? RemoveHealth (150) : RemoveHealth(0) );
}
int RemoveHealth(int hp)
{
health -= hp;
Debug.LogWarning (hp + " removed.");
return health;
}
If, if/else statements still long code for you. Try ?: statements. ? means if, : means else. You can do this in one long line too.
so this is basicly a long if/else if/else statement in a one long line of code.
Your answer
Follow this Question
Related Questions
Big numbers 2 Answers
Random.InitState 2 Answers
How to add force in random directions? 0 Answers
why did the script change 0 Answers