Hey guys! I had some quick questions about subclassing in C# and unity’s built in methods. I currently am having what I imagine is a fairly common issue where I have enemies and players with some similar component behaviors that I need to extend the base functions of slightly in order to tailor them specifically to what I want them to do. Seems like the perfect time to implement sub classes! So I went ahead and gave it a try and got everything working save for one thing. Code in the Update function of the base class does not seem to run at all ![]()
I tried messing around in the base class and turning the Update method public virtual but that caused compiler errors when I tried to override it. I was thinking about maybe trying to make the Update method in the base class a coroutine and then start that coroutine from the subclass? i figured before I dug down that rabbit hole I would come on here and post some code and see what people thought. First off here is the base class.
using UnityEngine;
using System.Collections;
public class ATBGovnah : MonoBehaviour {
public bool turnActive;
public float ATBProgress;
public float ATBspeed;
void Update () {
if (!turnActive) {
ATBProgress += Time.deltaTime * ATBspeed;
if (ATBProgress >= 1) {
setTurn();
}
}
}
public virtual void setTurn () {
turnActive = true;
}
}
and here is the subclass I am using to extend that class
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class playerATBGovnah : ATBGovnah {
public AudioClip ATBDing;
public UISlider ATBbar;
void Start () {
ATBbar = transform.FindChild("UIPanel").FindChild("ATB Progress Bar").GetComponent<UISlider>();
ATBbar.sliderValue = 0;
}
void Update () {
ATBbar.sliderValue = ATBProgress;
}
public override void setTurn () {
audio.PlayOneShot(ATBDing);
}
}
How should I go about doing this? What is the correct way to over ride the built in unity functions? Should I just make the Update code function of the base class a separate method and call it in the update function of the subclass?