- Home /
Subclassing no-go? (C#)
Hi :)
I'm creating a game which will have many forms of the same object, with many different functionalities.
I am trying to create a skeleton class which contains all of the shared properties of these objects. Then, I define it as the superclass to all the other objects.
That works fine and well, until... Anonymous typing.
Say I have the class BaseClass.
Then I have the class SubClass, which is a subclass of BaseClass
Finally, I have TestClass, which contains one variable of type BaseClass.
If I add BaseClass to a new gameobject, and try to add the gameobject to the variable in TestClass, it works fine.
But if I instead add SubClass, it does not work at all! It simply will not attribute its self to the variable!
How in blazes can I get this to work??
3 classes:
BaseClass:
using UnityEngine; using System.Collections;
public class BaseClass : MonoBehaviour { public string mytext; public int countA = 0; void Update () { IC(); }
public void IC()
{
countA++;
}
}
SubClass:
using UnityEngine; using System.Collections;
public class SubClass : BaseClass { }
TestClass:
public class TestClass : MonoBehaviour {
public BaseClass bc;
}
From what you say, it should work. Can you post your three classes please?
Not sure why this question got bumped, but that's not really an anonymous type. That's just treating a subclass like a base class- Polymorphism.
Answer by Demigiant · Mar 02, 2011 at 07:35 PM
Your code seems ok, and I use subclassing all the time without issues.
The only thing that comes to my mind, is that maybe you're storing bc "as SubClass", instead than "as BaseClass", and thus the type don't match.
If not, could you post the method you use to store/instantiate bc?
I do it all in Unity, non-runtime. The whole point of subclassing was so that all the subclassess could be treated as their superclass, thus making code allot simpler. I will try instantiating and adding the objects at runtime.
It works! Thanks for pointing me in the right direction. I can't believe I didn't try that before posting. Sorry for the dud post :(
P.S. I suppose you can still have it working via drag&drop in the editor, but you'll need a custom inspector to apply the correct typing.
Your answer
![](https://koobas.hobune.stream/wayback/20220613111017im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Creating an array of custom objects 1 Answer
Can I use lambda expressions or anonymous methods in JS? 1 Answer
Is Instance Of 3 Answers
How can I start fading out text upon setting it? 3 Answers
Accessing a private var from a subclass 2 Answers