Reputation: 65
I have lots of different enemies in my game. Each of these enemies have different scripts. When the player hits an enemy, I want the health variable in it's specific script to decrease.
I realize I could do something like this:
if(Target.getComponent<Enemy1script>()) Target.getComponent<Enemy1Script>().health -= Damage
However I have a lot of different types of enemies in my game and therefore lots of different scripts, meaning it's not that efficient. Because all of these scripts have one variable in common (health
), I'm wondering if you can just access their script component in general?
For example:
Target.getComponent<Script>().health -= 1
Upvotes: 0
Views: 2625
Reputation: 61
The solution to your problem is to create a base class called Enemy that stores the health and possibly contains some virtual behaviour functions. For each different type of enemy, your enemy class would inherit from the base enemy class.
For example:
Enemy.cs
public class Enemy : Monobehaviour {
public int health;
};
EnemyType1.cs
public class EnemyType1 : Enemy {
//Unique enemy behaviour goes here
};
This means that you can use
target.GetComponent<Enemy>().health;
to access the health of any enemy without needing to know specifically what it is.
Calling GetComponent is very resource intensive, so what I personally would do is
target.SendMessage("applyDamage", damageToDo, SendMessageOptions.DontRequireReceiver);
and then in your enemy class you would have
public class Enemy : Monobehaviour {
private int health;
public void applyDamage(int amount) {
health-=amount;
}
};
The unity docs do a good job of explaining what SendMessage is and how to use it. In summary, it tries to call that function on any script attatched to the object and will pass an argument to it. If you need to send multiple arguments then you will have to create a struct and send that instead. The final argument in SendMessage means that if it hits something that doesn't have the function, it won't cause the game to throw an exception and crash
Upvotes: 1