Hey Guys,
I’m trying to make a TowerDefense game and I have a problem when pressing my Upgrade() function, that currently is a Button with an OnClickEvent sitting on the UI of the selected turret.
I’m getting a NullReferenceException all the time and i just can’t figure out why.
Here is a Part of the upgrade function:
public void UpgradeOne()
{
if (turret.StandardTurretBuilt == true)
{
turret.FirstUpgradeTurret();
if (turret.isUpgradedOne == true)
{
Hide();
StandardTurretLevelTwo.SetActive(true);
}
}
This calls the following function:
public void FirstUpgradeTurret()
{
if (PlayerStats.Money < turretBlueprint.upgradeCostOne)
{
Debug.Log("Not enought money to upgrade!");
return;
}
Debug.Log("1");
PlayerStats.Money -= turretBlueprint.upgradeCostOne;
Destroy(turret);
Debug.Log("2");
GameObject _turret = (GameObject)Instantiate(turretBlueprint.upgradeOnePrefab, mouseOver.GetBuildPosition(), Quaternion.identity);
turret = _turret;
Debug.Log("3");
isUpgradedOne = true;
isUpgradedTwo = false;
isUpgradedThree = false;
isUpgradedFour = false;
Debug.Log("4");
GameObject effect = (GameObject)Instantiate(buildManager.buildEffect, mouseOver.GetBuildPosition(), Quaternion.identity);
Destroy(effect, 5f);
Debug.Log("5");
Debug.Log("Turret upgraded");
}
The Debug.Log()'s were just to find out where exactly the mistake was and it came out that the problem comes with the “turretBlueprint.upgradeOnePrefab”
Just to show you this is the “TurretBlueprint” script:
[System.Serializable]
public class TurretBlueprint {
public GameObject prefab;
public int cost;
public int sellLevelOne;
public GameObject upgradeOnePrefab;
public int upgradeCostOne;
public int sellLevelTwo;
public GameObject upgradeTwoPrefab;
public int upgradeCostTwo;
public int sellLevelThree;
public GameObject upgradeThreePrefab;
public int upgradeCostThree;
public int sellLevelFour;
public GameObject upgradeFourPrefab;
public int upgradeCostFour;
public int sellLevelFive;
}
I had the upgrade function and all the necessary information sitting on the cube and the cubes script where the turret is built on and it worked. But I wanted to move it to the turret itself because it makes more sense in my opinion and basically i tried to mainly copy everything to a different script. Maybe while doing that I messed up with some GameObjects that I brought into the wrong context but I’m not quite sure. I tried to fix it for a long time now trying different things but there seems to be something I’m not seeing.
If there is any code missing you might need to find the problem feel free to ask for it.
Any answers appreciated