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:
'T' only refers to a type, but is being used as a value here.
Is there a way to create an instance of the Plant like this:
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 {
// I would like to create Plants like this
build<T extends Plant>() {
if (T.cost <= game.money) { //'T' only refers to a type, but is being used as a value here.
this.plant = new T(this); //'T' only refers to a type, but is being used as a value here.
game.money -= T.cost; //'T' only refers to a type, but is being used as a value here.
}
}
}
// this is how I would build plants.
// altho I am not sure yet how to change Plant types using an UI with this aproach.
let c = new Cell();
c.build<Sunflower>();