- Home /
JS class inheritance woes. i.e. wtf?
Suppose I have two classes. One is a base class extending from MonoBehaviour. We'll call it Base. There's a method in this class called DoStuff(), which is called at various points in Update. I have a second class called Thing that extends from Base. What I'm wondering is, can I override the DoStuff() method in Thing so that when it's called via the base class, the derived method is used?
Example:
class Base extends MonoBehaviour {
function Update() { DoStuff(); }
function DoStuff() { //do some stuff }
}
and....
class Thing extends Base {
function DoStuff() { //do some different stuff }
}
Will this ever work? It seems like Thing's DoStuff() is completely ignored. I'm probably missing something.
Answer by Mike 3 · Sep 27, 2010 at 01:39 AM
You need to make both versions of DoStuff virtual, which means that when DoStuff is called, it'll look for most specific version of the function
As it is now, they're both completely different functions with the same name, so from Update, DoStuff references the base class's version, not your extending class
e.g.
class Thing extends Base {
virtual function DoStuff() //if Base has this as virtual too, Update calling DoStuff will call this function
{
//do some different stuff
}
}
See, I knew I was missing something :) Thanks a lot $$anonymous$$ike, just what I was looking for.
Answer by Dreamora · Sep 26, 2010 at 10:38 PM
This will work yes. But you have to cast it to class Thing, otherwise its considered class base and the function of class base will be called.
The redeclaration in the extended class does not make it go away in the base class.
Your answer
![](https://koobas.hobune.stream/wayback/20220613073959im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Change a Class in the inspector 1 Answer
Making a class publicly available 3 Answers
Creating a dynamic array of objects of custom class 1 Answer
How to Typecast JS Variables as C# Classes? 0 Answers
Polymorphism and ScriptableObjects 1 Answer