Playing around with a tower defense tutorial. After adding the ability to upgrade towers, upon placing a tower it goes straight to the upgraded second tower; not the base value. There are three possible levels - 1,2, and 3.
using UnityEngine;
using System.Collections;
public class PlaceTower : MonoBehaviour {
void Start()
{
gameManager = GameObject.Find("GameManager").GetComponent<GameManagerBehavior>();
}
private GameManagerBehavior gameManager;
public GameObject BlueTowerPrefab;
private GameObject BlueTower;
private bool canPlaceBlueTower() {
return BlueTower == null;
}
void OnMouseUp() {
//2
if (canPlaceBlueTower ()) {
//3
BlueTower = (GameObject)
Instantiate(BlueTowerPrefab, transform.position, Quaternion.identity);
//4 Upgrading with Gold
if (canPlaceBlueTower ()) {
//Your code stays the same before
} else if (canUpgradeBlueTower()) {
BlueTower.GetComponent<BlueTowerData>().increaseLevel();
gameManager.Gold -= BlueTower.GetComponent<BlueTowerData> ().CurrentLevel.cost;
}
}
}
//Test upgrade Capability
private bool canUpgradeBlueTower() {
if (BlueTower != null) {
BlueTowerData bluetowerData = BlueTower.GetComponent<BlueTowerData> ();
TowerLevel nextLevel = bluetowerData.getNextLevel();
if (nextLevel != null) {
return true;
}
}
return false;
}
There may be a section to discuss this kind of stuff. I don’t know the tutorial specifically, but it looks as though whatever ‘TowerLevel nextLevel’ is, is returning non-null, thus allowing the upgrade.
Perhaps you want to move that upgrade/check to some other place that is accepting user input to do an upgrade, rather than just in the placement area …
First you check if you can place blue tower and if you can (i.e. it’s null) then you create it. Now blue tower is not null anymore but then you check if you can create it again (this time it will always return false because you just created it) and then when it returns false you enter the else clause which upgrades the tower in the same mouse click.
The simple way to fix it (at least to fix the problem I described above, there seems to be a lot of other issues):
void OnMouseUp()
{
if (canPlaceBlueTower())
{
BlueTower = (GameObject)
Instantiate(BlueTowerPrefab, transform.position, Quaternion.identity);
// Upgrading with Gold
else if (canUpgradeBlueTower())
{
BlueTower.GetComponent<BlueTowerData>().increaseLevel();
gameManager.Gold -= BlueTower.GetComponent<BlueTowerData>().CurrentLevel.cost;
}
}
Next time use the forum’s code tags to enclose your code in so it’s readable.