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.