- Home /
Inheriting method that uses an instance property
I've got a base class and a subclass like so:
public class DCBaseNode : Node {
public GameObject goRef;
private Color selectedColor = Color.cyan;
public DCBaseNode(long id) : base(id){
}
public virtual void onTouchEnter(){
goRef.renderer.material.color = this.selectedColor;
}
}
public class DCPauseNode : DCBaseNode {
public Color selectedColor = Color.green;
public DCPauseNode(long id) : base(id){
}
}
What I thought would happen was that an instance of DCPauseNode
would turn green, since the inherited onTouchEnter()
method references this.selectedColor
, which is 'overridden' in DCPauseNode
, but that doesn't work. What am I missing?
Answer by dhandley · Aug 12, 2014 at 05:42 PM
You're not really overriding the field, it's more like you're hiding the selectedColor in each class from the other class. ie: DCPauseNode can't access DCBaseNode.selectedColor because it is private DCBaseNode can't access DCPauseNode.selectedColor because it is a completely separate variable in a derived class.
Perhaps you could declare the color in the base class only, make it accessible to the derived classes and set it as desired in each derived class. Something like:
public class DCBaseNode : Node {
public GameObject goRef;
protected Color selectedColor = Color.cyan;
public DCBaseNode(long id) : base(id){
}
public virtual void onTouchEnter(){
goRef.renderer.material.color = this.selectedColor;
}
}
public class DCPauseNode : DCBaseNode {
public DCPauseNode(long id) : base(id){
selectedColor = Color.green;
}
}
Ah—I actually meant to write that selectedColor is public in the base class; would that make a difference? In any case, setting it in the Constructor is easy enough!