简体   繁体   中英

Unity C# Calling script via string with varying name

My goal is during my combat script, to call a death function from CombatHandler to the script thats attached to the enemy. The problem is that enemy's do not stay the same, thus meaning the script name will have to change! For example, one enemy will have a script named EnemySalamander, the next will have a script called EnemyGoblin (these controlling the enemy stats, ect)

Here is the Code snippet from combat handler

if (healthEnemy < 0) {
    healthEnemy = 0;
    Debug.Log ("You killed a "+nameEnemy+". You have "+ps.health+" health left!");
    //pcc.gameObject.scriptname.death ();
    clearEnemy ();
} else if (ps.health < 0) {
    clearEnemy ();
    ps.health = 0;
    Debug.Log ("You died with the enemys health left at " + healthEnemy);
}

I have commented out the part where I need to call the death method on the gameObject's script. Pcc.gameobject is where I have direct access to the gameObject(Enemy) I am attacking.

This is exactly what GetComponent() does. The official documentation doesn't make it clear that passing in a class will also find any component that is a subclass of the indicated Type, but it will:

Getting derived class using base class in GetComponent?

Yes, this will work as I believe you expect it to.

There isn't a decent chunk of text from the Unity Answers QA to really quote. It goes from that straight into an implementation and results.

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