Skip to content

Instantly share code, notes, and snippets.

@BenTristem
Last active March 15, 2018 17:00
Show Gist options
  • Save BenTristem/1bdc2d781b39bf293ec8be489622ea0b to your computer and use it in GitHub Desktop.
Save BenTristem/1bdc2d781b39bf293ec8be489622ea0b to your computer and use it in GitHub Desktop.
A circular or ring buffer system for placing RTS towers. Part of https://www.udemy.com/unitycourse2
public class TowerFactory : MonoBehaviour {
[SerializeField] Tower towerPrefab;
[SerializeField] int towerLimit = 5;
Queue<Tower> towerQueue = new Queue<Tower>();
public void AddTower(Waypoint waypoint)
{
Vector3 newPos = waypoint.transform.position;
if (towerQueue.Count < towerLimit)
{
InstantiateNewTower(waypoint, newPos);
}
else
{
MoveExistingTower(waypoint, newPos);
}
}
private void InstantiateNewTower(Waypoint waypoint, Vector3 newPos)
{
var newTower = Instantiate(towerPrefab, newPos, Quaternion.identity);
newTower.waypoint = waypoint;
waypoint.isPlaceable = false;
towerQueue.Enqueue(newTower);
}
private void MoveExistingTower(Waypoint newWayPoint, Vector3 newPos)
{
var oldTower = towerQueue.Dequeue();
oldTower.waypoint.isPlaceable = true;
newWayPoint.isPlaceable = false;
oldTower.waypoint = newWayPoint;
oldTower.transform.position = newPos;
towerQueue.Enqueue(oldTower); // stick it back on top of the pile
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment