Alright, this has been a thorn in my side for two days now. I have a bullet class that removes a certain amount of health from the enemy. Problem is, UpdateHealth () [The method I use for adding/subtracting from health] is located in the enemies script grandparent [EnemyPrototype.cs inherits from Enemy.cs which also inherits from Humanoid.cs].
You’re thinking, “Okay that’s easy, just use this bit of code into the bullet”:
Nope wouldn’t work because in the future I will have more than one enemy type, which will have an entirely different script [Still inherting from Enemy.cs].
So I need to somehow access others script, in order to call method UpdateHealth(), without knowing it’s name.
If EnemyPrototype inherits from Enemy, you can do a GetComponent for Enemy instead, and access all the parts of EnemyPrototype that it inherited from Enemy.
A other option is for you to look into interfaces, you could make a interface called IDamageable that has a UpdateHealth method declared, than anything that implements the interface will need to have its own UpdateHealth method. Than you can use the GetComponent on IDamageable
Thank you! I didn’t realize you could grab parent classes from another class like that! I thought it would just end up creating a new instance of the parent class.
yeah you can do that, also GetComponent wont make a instance of anything, if you ask it to get something that isnt there, or something that cant be cast to what you want it will return null.
so doing a GetComponent and making sure it isnt null is a good way to check for the existence of a component as well.
EDIT:
also a nice little trick is to declare a method as virtual in the parent class, than override it in the inheriting class, you can still treat it like the parent class after that but define what the method does in the child class.