How to call an override function if it was overrode. If not, just call the parent's function
Hi!
In my game I have guns shooting one bullet at the time and a weapon that shoots in arc, several bullets in a single shot. I created a class named Shooter, that shoots a bullet when the shoot() function is called. I created a class nemed ArcShooter that inherits Shooter class and override the shoot() function.
The Shooter class has the Update method below:
void Update(){
if(firing){
if(bullet_deltaTime >= bullet_interval){
shoot();
bullet_deltaTime = 0;
} else {
bullet_deltaTime += Time.deltaTime;
}
}
}
Is there a way to Shooter class call the override function in its children if there is an override, and call the parent's shoot() function if there is no override function?
I tried to call this.shoot(), but the program always calls the parent's function.
Thanks
Caio
Answer by UnityCoach · Feb 02, 2017 at 07:50 AM
By "children", you mean derived classes? And by "parent", you mean base class, right? If so, that's the way inheritance is meant to work.
Say you have a WeaponBase class, that has a method Shoot (), like :
public abstract class WeaponBase : MonoBehaviour
{
public virtual void Shoot ()
{
Debug.Log ("Base Shoot");
}
}
Then you create a new derived class
public class RPG : WeaponBase
{
public override void Shoot ()
{
base.Shoot ();
Debug.Log ("RPG Shoot");
}
}
Calling Shoot () on the derived class, will call the override method.
Answer by LobsterInJunk · Feb 02, 2017 at 06:34 PM
What do you mean by "override"? Keyword override mean actually what you want. You need to mark method shoot in paren class with virtual keyword and method shoot in child class with override keyword (if you override this method in this child). If you dont use this keywords, you childs method shoot() hides parents methos shoot().
Your answer
Follow this Question
Related Questions
How can i move object between two positions ? 1 Answer
Menu object not responding 0 Answers
Scripting Help desperately needed. 1 Answer
Update() and FixedUpdate() not running on C# scripts 0 Answers