I have a class called BuildingObject, and I need to make subclasses of the different types. When I make a subclass, the subclass doesn’t even show up when I try to make a variable type. Another problem, is when my variable of type BuildingObject stores a subclass, how do I access the subclass variables?
Editor script:
public class BuildingObject {
[SerializeField]
private GameObject _prefab;
[SerializeField]
private string _name;
public BuildingObject(string name, GameObject go) {
_name = name;
_prefab = go;
}
public GameObject Prefab {
get { return _prefab; }
set { _prefab = value; }
}
public string Name {
get { return _name; }
set { _name = value; }
}
}
Type of building:
public class MoneyGeneratorObject : BuildingObject {
[SerializeField]
private int _moneyPerSecond;
[SerializeField]
private int _maxMoneyHeld;
public MoneyGeneratorObject(string name, GameObject go, int moneyps, int maxheld) : base(name, go, moneyps, maxheld) {
_maxMoneyHeld = maxheld;
_moneyPerSecond = moneyps;
}
public int MoneyPerSecond {
get { return _moneyPerSecond; }
set { _moneyPerSecond = value; }
}
public int MaxMoneyHeld {
get { return _maxMoneyHeld; }
set { _maxMoneyHeld = value; }
}
}
Editor script:
private BuildingObject selectedObject;
selectedObject.Name = "Random Name";
selectedObject.MaxMoneyHeld = 1000; // This doesn't work
BuildingObject is your baseclass which does not have MaxMoneyHeld property,
but your inheritted class MoneyGeneratorObject does have MaxMoneyHeld property aswel as any property on your base class (Name… etc).
private MoneyGeneratorObject selectedObject;
selectedObject.Name = "Random Name"; // This is accessable from the base class
selectedObject.MaxMoneyHeld = 1000; // This will work because we are on the inheritted class
The subclass doesn’t show up because the class contains an error.
In your MoneyGeneratorObject() constructor, you are calling the base() constructor and passing 4 arguments but the constructor in the base class BuildingObject only accepts 2 arguments.
public MoneyGeneratorObject(string name, GameObject go, int moneyps, int maxheld) : base(name, go) { // not, moneyps, maxheld) {
_maxMoneyHeld = maxheld;
_moneyPerSecond = moneyps;
}
To access the fields within the subclass, you need to check if the object is derived from the appropriate type, then you need to cast the object to that type before you can read or write those fields (or call subclass methods).
private BuildingObject selectedObject;
selectedObject.Name = "Random Name";
if (selectedObject is MoneyGeneratorObject) {
((MoneyGeneratorObject) selectedObject).MaxMoneyHeld = 1000;
}
The above gets unwieldy when you start to have very many subclasses with divergent structures.
For the moment, it should be sufficient but you should probably revisit this issue again if your code starts getting bloated with exceptional cases.