- Home /
A Variable that can hold different class Objects
I've 2 classes :
[System.Serializable] public class A {
[SerializeField] public bool apply;
[SerializeField] public float pointInSpeedDuration ;
[SerializeField] public float pointIntervalbetweenSpeedUp ;
[SerializeField] public float variablePointSpeed ;
}
[System.Serializable] public class B{
[SerializeField] public bool apply;
[SerializeField] public float reverseDuration ;
}
Somewhere in a third class I'm creating object of these classes :
public class LevelController : MonoBehaviour {
public int levelIndex ;
public A objA = new A();
public B objB = new B();
}
However I need only one class(A or B) at a time ,
please let me know if I can do something so that I can have a single variable which can hold class A or B:
public class LevelController : MonoBehaviour {
public int levelIndex ;
public var obj = new A();
//OR
public var obj = new B();
}
for me, "var" is not working in the above example
Answer by ParanoidSnail · Mar 25, 2015 at 10:12 AM
What you are looking for is called Inheritance. You can find a lot of information about this on google.
http://unity3d.com/learn/tutorials/modules/intermediate/scripting/inheritance http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29
I'm not very good in C# concepts, however if I create a class C that inherits from Class A works well but how to inherit it from class B at same time , can I change inheritance at runtime ?
[System.Serializable] public class C: class A{
}
you want a class A with any common things, in your case the apply variable. Then you have B and C that inherit from A and as they inherit, they are A.
In your other script you have
public A myInstance;
now since B and C are A (inheritance) they can fit in that spot. Via that variable only what is in A is accessible. SO you would have to cast to access lower level variables or look into polymorphism (roooh that surely is a fancy name ). It would be a little long to explain so google is your friend.
Thanks fafase for your suggestion, polymorphism is ok , however my problem is the non-$$anonymous$$onoBehaviour derived class are not serializable As mentioned somewhere , I'm trying to achieve this , however its not visible in inspector :
public class Base {...}
public class Triangle : Base {...}
public class Square : Base {...}
public class Circle : Base {...}
public class $$anonymous$$yBigClass {
public Base m_i_am_polymorphic; // this can be assigned a Triangle, Square, Circle, or anything that inherits from Base
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613191211im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instancing class automatically? 2 Answers
All Arrayinstances get changed -1 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Getting NullReferenceException when creating class instance using List 1 Answer