Tower Factory code question

I’m following the video and he wants us to make the script so that it will log when you place too many towers in the scene, and to stop instantiating any more. And I figured it out, but I don’t understand why the int towerCount; only works when it’s outside of the function rather then in it.

(The code with the towerCount inside the function - the one that DOESN’T work)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TowerFactory : MonoBehaviour {

[SerializeField] int towerLimit = 5;
[SerializeField] Tower towerPrefab;

public void AddTower(Waypoint baseWaypoint)
{
    int towerCount = 0;

    if (towerCount < towerLimit)
    {
        InstantiateNewTower(baseWaypoint);
        towerCount++;
    }
    else
    {
        MoveExistingTower();
    }
}

private static void MoveExistingTower()
{
    print("No more towers can be placed");
}

private void InstantiateNewTower(Waypoint baseWaypoint)
{
    Instantiate(towerPrefab, baseWaypoint.transform.position, Quaternion.identity);
    baseWaypoint.isPlaceable = false;
}

}

(The code with the towerLimit outside the function - the one that DOES work)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TowerFactory : MonoBehaviour {

[SerializeField] int towerLimit = 5;
[SerializeField] Tower towerPrefab;
int towerCount = 0;

public void AddTower(Waypoint baseWaypoint)
{

    if (towerCount < towerLimit)
    {
        InstantiateNewTower(baseWaypoint);
        towerCount++;
    }
    else
    {
        MoveExistingTower();
    }
}

private static void MoveExistingTower()
{
    print("No more towers can be placed");
}

private void InstantiateNewTower(Waypoint baseWaypoint)
{
    Instantiate(towerPrefab, baseWaypoint.transform.position, Quaternion.identity);
    baseWaypoint.isPlaceable = false;
}

}

Any help would be much appreciated.

On the piece of code that the doesn’t work you are setting the towerCount variable to 0 every time the method is called and then incrementing it. With the variable outside it doesn’t reset to 0 and so accurately counts the number of towers set.

1 Like

Ohh okay, I thought that it would keep it’s old value while in the method so that makes sense, sweet thank you.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms