- Home /
What is the purpose of this function? "protected virtual void Init() { }"
Hello, I'm a novice coder and don't quite understand all the articulates of C#, so when I look at other people's source code to learn from it some things I don't quite understand.
The one I'm looking at in particular is [Dani's LudumDare 45 vlog][1]
[Here is the source code for his "Actor" script I'm looking at][2]
I'm currently trying to make a 2D game which contains player's and enemies and I understand that you can have one script with multiple declaring variables for that particular group of actors to save on coding.
On line 35 - 43 there's a particular function that is called which I'm failing to understand the purpose of, here is a snippet of that particular code
protected virtual void Init() { }
private void Awake() {
ps = GetComponentInChildren<ParticleSystem>();
em = ps.emission;
rb = GetComponent<Rigidbody2D>();
Init();
sr = GetComponent<SpriteRenderer>();
dColor = sr.color;
}
An "Init" function is I assume, overwritten but there's no parameters or code in the actual function and then is called in the "Awake" function. What is the purpose of this function? As well as what benefit is having the function be protected? Thanks in advanced [1]: https://youtu.be/YMWnwBpUgoI [2]: https://github.com/DaniDevy/LudumDare45/blob/master/LD45/Player/Actor.cs
Answer by Bunny83 · Aug 23, 2020 at 01:15 PM
Well, because PlayerMovement as well as Enemy are derived from Actor and override the Init method. This is just basic / fundamental OOP, so I'm not sure what kind of answer or explanation you expect to get. The base class implements a virtual method that can be overridden by a derived class to provide additional / customized initialization code.
protected is just the visibility of that method. So this method can not be seen or called from outside the Actor class or any descendents because it's only relevant for the internal function of this class / those classes. In general you should have everything either private or protected by default and only make things public that really need to be public.
Ah I understand now. The main actor class won't have anything in the Init() function but other classes derived from it can have their own specific implementation of Init(). This actually answered both my questions thank you
Your answer
Follow this Question
Related Questions
Initialising List array for use in a custom Editor 1 Answer
i have a problem with reloading with Time.time 2d game c# Unity 2020.2 1 Answer
Multiple Cars not working 1 Answer
Dictionary in second script empty 1 Answer
How would i calculate the size of a 2D area closed off by multiple colliders? 1 Answer