I am currently working on a basic TD game, and I’m having a little trouble dealing with upgrades. As of now, I have a bunch of preset-tiles placed on my map, and if you click those towers, it will spawn a tower on top of that tile if the provided conditions are met (if you have enough $ and there isn’t already another tower there).
However, when it comes to upgrading, I’m running into problems. Ideally, what happens is that if I have enough money and I click on the tower/tile, the upgraded tower will replace the current tower. The issue is that I’m unable to get rid of the pre-existing tower.
void OnMouseUpAsButton() {
GameObject tower;
if (!has_tower) {
if (spawn.GetKash() < cost) {
GetComponent<AudioSource> ().Play ();
}
else {
tower = Instantiate (tower_prefab);
tower.transform.position = transform.position + Vector3.up;
spawn.MakeKash (-cost);
has_tower = true;
}
} else {
if (!upgraded) {
if (spawn.GetKash() < upgrade_cost) {
GetComponent<AudioSource> ().Play ();
}
else {
//Destroy(tower);
GameObject upgrade = (GameObject)Instantiate (upgrade_prefab);
upgrade.transform.position = transform.position + Vector3.up;
spawn.MakeKash (-upgrade_cost);
upgraded = true;
}
}
}
}
If I don’t initialize tower, then I get an error as it may be unassigned in the Else statement. However, if I do initialize tower, what happens is that clicking only results in spawning a bunch of towers without destroying any single one of them.
Any help would be greatly appreciated!