- Home /
The question is answered, right answer was accepted
How to save prefabs with private data through inheritance
I have a 2 class inheritance chain, Builing - House. I want to create a house with values set from the classes but they can't be public, which means I can not edit them in the inspector. So my questions is, how do I set private values so I can use my inheritance tree properly?
Extra info: If I make another class, say SmallHouse, as a child of House then I can not add the SmallHouse script to a list of Houses which is important. It is actually why I need so hard code this information somewhere.
Answer by Maerig · Jul 01, 2014 at 02:28 AM
The protected
modifier makes a field visible for a class and its derived classes only, is it what want ?
Well I am using protected but the issue is this class seems redundant.
public class SmallHouse : House {
//All of these propeties are set through the inherited protected members.
public SmallHouse ()
{
this.buildingName = "Small House";
this.costWood = 750;
/*properties omitted due to repitivity.*/
}
}
I made this class to actually give the properties some value but there has to be a better way to do it.
I think there is nothing wrong with your implementation, but in C# you could also do this using abstract or virtual properties, although I'm not sure which solution is better. Anyway, if this is more to your liking, here is how you would do it :
// Father class
protected abstract string BuildingName {
get;
}
protected abstract int CostWood {
get;
}
// Child class
protected override string BuildingName {
get {
return "Small House";
}
}
protected override int CostWood {
get {
return 750;
}
}
You can also do this without using abstract members and simply assign them values in the child class in a constructor (or Awake if using $$anonymous$$onoBehaviour).
It really depends if you are going to have Houses running around as well as SmallHouses.