Issue
I was trying to implement a neat way to build multiple Plants (inspired by plants vs zombies). To make it easy to add more plant Types I wanted to make the cost and dmg of the plant static so I can set it once for all Plants of this type.
In this case I have only one Plant (Sunflower), now I would like to instantiate the Sunflowerplant. In the build method in the Cell class.
When doing it like this I get the error:
Cannot create an instance of an abstract class.
which is understandable for me. So is there a way to only be able to pass non abstract classes which extend from Plant as a Parameter for the build()
methode or do I have to implement some sort of if (!c isAbstract)
abstract class Plant {
public static dmg: number;
public static cost: number;
constructor(cell: Cell) {
this.cell = cell;
}
cell: Cell;
}
// I would like to create more Plants like this
class Sunflower extends Plant {
public static dmg = 0;
public static cost = 50;
cell: Cell;
constructor(cell: Cell) {
super(cell);
}
}
class Cell {
build(c: typeof Plant) {
if (c.cost <= game.money) {
this.plant = new c(this); //Cannot create an instance of an abstract class.
game.money -= c.cost;
}
}
}
// this is how I would build plants.
let c = new Cell();
c.build(Sunflower);
Solution
You can do it like this:
class Cell {
build<T extends Plant>(plant: (new (cell:Cell) => T)) {
const plantInstance = new plant(this);
}
}
Answered By - Jamiec
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.