Reputation: 3
I'm creating a dialogue system and I wanna use polymorphism to make the job easier so I have a class thats the dialogue tree which holds List dialogue_tree... and then I have TextBoxNPC,TextBoxText,TextBoxItem etc so I can have each page display a different type of dialogue box if I so desire. each TextBox holds an enum of what type of textbox it is and the problem arrises when I want to change variables that arn't in the base class.
public class Dialogue_Tree
{
List<TextBox> dialogues = new List<TextBox>();
public Dialogue_Tree()
{
dialogues.Add(new TextBoxNPC());
dialogues[0].
}
}
if in textboxnpc I have Sprite npc_portrait I can't change it cause its being treated as TextBox. so even if I cast it, I get a null exception is there anyway to do this?
my only other option would be having only a single class TextBox and it having every variable needed for every different type of dialogue but then theres like 35 unused variables per textbox page which seems like a waste of resources.
Upvotes: 0
Views: 31
Reputation: 74710
You've got your understanding of polymorphism upside down. If you had a drawing program that used this polymorphic:
abstract class Shape {
public int X = 0;
public int Y = 0;
}
class Rectangle:Shape {
public int Width = 10;
public int Height = 20;
}
class Circle:Shape {
public int Diameter = 50;
}
You wouldn't, in the parent class, look at the type of the child and do something different:
foreach(Shape s in _listOfShapes){
if(s is Circle c)
myCanvas.DrawCircle(c.X,c.Y,c.Diameter);
else if(s is Rectangle r)
myCanvas.DrawRectangle(c.X,c.Y,r.Width,r.Height);
}
You create a way to treat all the shapes the same:
abstract class Shape {
public int X = 0;
public int Y = 0;
abstract void DrawYourself(Canvas c)
}
class Rectangle:Shape {
public int Width = 10;
public int Height = 20;
override DrawYourself(Canvas c){
c.DrawRectangle(base.X,base.Y,this.Width,this.Height);
}
}
class Circle:Shape {
public int Diameter = 50;
override DrawYourself(Canvas c){
c.DrawCircle(base.X,base.Y,this.Diameter);
}
}
Now all shapes know how to draw themselves on a canvas (that the parent owns) you treat them all as plain old shapes:
foreach(Shape s in _listOfShapes){
s.DrawYourself(myCanvas);
}
Upvotes: 1