r/UnityHelp • u/Hmmmm___0 • 3h ago
Virtual and Override question
Hello Unity3D subreddit!
Currently am working on a Game Project for school, and am wondering how I would go about grabbing reference to a parent’s already overridden function?
What I mean is. I have a base class, called EnemyBase. It stores some variables and key functions all enemies would share. I also have virtual functions that outline specific behaviors (idle, chase, attack, hurt) so that each enemy that inherits said function can modify that as needed.
Enemy_1 inherits from EnemyBase, and has those functions overridden with all the necessary behavior.
Now, I am looking to implement Enemy_2. This enemy, aside from its attack behavior, will behave pretty closely to Enemy_1. What I would *like* to do, is to have Enemy_2 inherit from the Enemy_1 class and call upon the overridden functions defined in Enemy_1 for its own logic. Is there any viable way to do that?
Hopefully that outlines the source of my question, can clarify further in the comments :D
1
u/Vonchor 3h ago
check out 'base'
If I understand you correctly, you want to call a method which inherits from a method in a base class and you want to also use the code in the overridden class?
In the overridden class just use the base keyword to call the overridden method within the overriding method.
Hope it helps
1
u/Demi180 3h ago edited 3h ago
It’s not super clear if you’re asking about calling functions that both E1 and E2 override or ones that only E1 does, and where in E2 you’re trying to call them from. But the answer is simple, regardless:
If a function Foo() is virtual and overridden, calling it normally will use the furthest override for the given object’s type, regardless of the type it’s called on. So if enemy instance e is an E1, even if you reference it as an EB, calling e.Foo() from outside, or just Foo() from inside will invoke E1.Foo().
If you’re calling from inside E2 and you want to specifically invoke E1.Foo(), you can use the base keyword. Calling base.Foo() will call the version that’s available to E1. It’s been a while since I tried but I think you can also call E1.Foo() rather than using base.base.base… if you have a long chain of inheritance.