- Home /
How can I access an inherited method from a separate (collided) object?
So, in order to make development a bit easier, I decided to create custom classes for projectiles and enemies. The enemy class contains health and health related functions, and the projectiles contain damage variables which were previously passed into it.
Before I created the classes(and only had one type of enemy and one type of projectile, I simply had my bullet get the(predictably named) script component and simply call the function(and passing the damage as a parameter)
Hackishly retyped code, since I'm at a different computer.
Bullet.JS:
OnColissionEnter( c : collision){
if(c.tag == "Enemy"){
c.getComponent(EnemyHealth.JS);
EnemyHealth.doDamage(bulletDamage);
}
}
And the doDamage logic handled whether or not the enemy was destroyed by the impact or not, etc.
But now since each enemy is often its own subclass, the script name is different each time, so I'm having a problem figuring out how to access my doDamage method since a number of my enemies have unique script names based on their subclass.
Is there any way to somehow grab the first script, all scripts, or a dynamic script using getcomponent, is there a different way of doing this, or would redesigning it to not be dependent on getcomponent be a better idea?
Note: I'm using UnityScript.
Edited for spelling.
Answer by PAEvenson · Jan 10, 2013 at 02:26 PM
var EnemyHealth= c.GetComponent<[BaseClassGoesHere]>();
You just need to make sure you have the doDamage function in the base class and overrides int the subclasses.
That's the point of having a base class ;) When an object is derived from a base class it has two "types". It's own type and the type of the base class. You can access and object by a base class reference but you can only access things which are defined in the base class since from the compilers point of view you just have a base class.
Virtual functions allows a derived class to "reimplement" the function, so when using a base class reference and execute the function you will execute the new function in the derived class.