简体   繁体   中英

How to get any script component from a Game Object

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

Solution

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.

Recommendation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM