Hey,
I am currently making a game unsurprisingly enough and I have decided to make a base class that ALL classes in the game derive from like they normally do with MonoBehaviour, and the base class itself derives from MonoBehaviour. This is fine, something I know how to do. The only problem I have run into is that I want to make an “Init” funtiction that gets called AFTER the Start function in the GameBase class has been called. I know I can do this by making a virtual function in the base then overriding it in the derived class, but it isn’t quite what I want. So my question is, how do I make a function that is called in the derived class like so:
void Init() {
}
Rather then the normal:
public override void Init() {
}
It is similar to how you can use Start() which is called from the MonoBehaviour class; but I don’t want to use Start because I need to be called from a Start function resulting in the derived classes to initialize after the base class.
Thanks,
Drummss
I might be COMPLETELY wrong, and probably am, but my understanding is that there’s nothing fundamentally unique about the Awake(), Start(), Update(), etc… functions in themselves, but rather that Unity goes through when it’s compiling and basically makes lists of all of them according to their names (through some kind of reflection maybe?), then forces them to run when and how it wants them to over the course of the program’s life.
I don’t think you’re going to find the kind of answer that you’re looking for, as it’s not some secret c# keyword to get this functionality.
As Lysander says, Unity uses reflection to get those methods by their string name and calls them directly. This is kind of poor programming though, and with all of their newer code, Unity is using interfaces and overrides like a proper C# library rather than hardcoded string names.
As to your original question… is it just that you don’t want to have to type the word “override”? Because if so, that’s a dumb reason.
But if that’s really what you want to do, you could use SendMessage to call it by string name:
public class MyBaseClass {
void Start() {
SendMessage("Init");
}
but keep in mind this will call Init() on every component on the game object if it exists.
There are other ways to structure it but we’d probably need to know what you’re trying to do and why you don’t want to use “override”.
Alright thanks for the answers, I will just use overriding ^.^