Create a system for a a strategy game, this system will handle how to send the builders…
- User
Create a system for a a strategy game, this system will handle how to send the builders to construct buildings
- Its name will be BuilderManager
- When a building is created, it will call the builder manager and the building will be added to the queue
- When a Builder is created it will call the builder manager ant he will be marked as an available builder to be handled by the builder manager
- When there is a building pending to be build and there is a builder available it will call a corountine to wait a time and fill the health bar and the builder will be marked as busy
- When it is night time if the bulding is being constructed it is paused and the builder will go to his house
- The script knows if there is day or night with these subscriptions GameManager.Instance.OnDayStart += DayAction; GameManager.Instance.OnNightStart += NightAction;
- If a building is destroyed it will be marked as destroyed in a queue, the building will notify the builder manager if this happens
- If it is day the manager will check if there are buildings destroyed, the builders will go out of its house and the builder manager will prioritize the buildings destroyed before the new ones
- Assistant
To implement the BuilderManager concept as specified, we'll need to encapsulate various functionalities like maintaining a queue for construction, tracking available builders, managing the construction process, handling day/night cycle interruptions, and prioritizing rebuilding destroyed structures.
Below is a pseudo-code outline for the BuilderManager class, considering the constraints and requirements mentioned:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BuilderManager : MonoBehaviour { private Queue<Building> constructionQueue = new Queue<Building>(); private Queue<Building> destroyedQueue = new Queue<Building>(); private List<Builder> availableBuilders = new List<Builder>(); private List<Builder> busyBuilders = new List<Builder>(); private bool isNightTime = false; void Start() { // Subscribe to day/night events GameManager.Instance.OnDayStart += DayAction; GameManager.Instance.OnNightStart += NightAction; } void Update() { if (!isNightTime && availableBuilders.Count > 0) { AssignBuildersToConstruction(); } } public void AddBuildingToQueue(Building building) { constructionQueue.Enqueue(building); } public void AddBuilder(Builder builder) { availableBuilders.Add(builder); } private void AssignBuildersToConstruction() { while (availableBuilders.Count > 0 && (destroyedQueue.Count > 0 || constructionQueue.Count > 0)) { Building buildingToConstruct = destroyedQueue.Count > 0 ? destroyedQueue.Dequeue() : constructionQueue.Dequeue(); Builder builder = availableBuilders[0]; availableBuilders.RemoveAt(0); busyBuilders.Add(builder); StartCoroutine(ConstructBuilding(builder, buildingToConstruct)); } } private IEnumerator ConstructBuilding(Builder builder, Building building) { builder.MarkAsBusy(); while (building.GetConstructionProgress() < 100 && !isNightTime) { building.Construct(); // Simulates the construction over time. yield return new WaitForSeconds(1f); // Wait time simulating construction work in progress. } if (building.GetConstructionProgress() >= 100) { building.MarkAsComplete(); busyBuilders.Remove(builder); builder.MarkAsAvailable(); availableBuilders.Add(builder); } } private void DayAction() { isNightTime = false; foreach (Builder builder in busyBuilders) { // Resume construction if it was paused due to night time. StartConstruction(builder); } } private void NightAction() { isNightTime = true; foreach (Builder builder in busyBuilders) { builder.GoToHouse(); // Builder goes home for the night. } } public void BuildingDestroyed(Building building) { destroyedQueue.Enqueue(building); building.NotifyBuilderManager(); } void OnDestroy() { // Unsubscribe to prevent memory leaks. GameManager.Instance.OnDayStart -= DayAction; GameManager.Instance.OnNightStart -= NightAction; } private void StartConstruction(Builder builder) { // Find the building associated with the builder. Building building = /* logic to find the builder's assigned building */ StartCoroutine(ConstructBuilding(builder, building)); } } // The Building class should have methods like Construct(), GetConstructionProgress(), NotifyBuilderManager(), MarkAsComplete(). // The Builder class should have methods like MarkAsBusy(), GoToHouse(), MarkAsAvailable().This pseudo-code provides a high-level outline for the BuilderManager system. The actual implementation of
Construct(),GetConstructionProgress(), and other methods in the Building class, andMarkAsBusy(),GoToHouse(), andMarkAsAvailable()in the Builder class will depend on the specifics of your game's mechanics.Moreover, proper error handling and checks should be included for edge cases, such as when a building is destroyed mid-construction or when the builders are reassigned tasks during the night-to-day transition.
- User
Complete the start construction method
- Assistant
To complete the
StartConstructionmethod, let's assume that you have some way to track which building a builder was constructing before nighttime. In a more advanced approach, you might have aDictionary<Builder, Building>to remember this association. However, for simplicity, let's just assume eachBuilderobject has an associatedBuildingthey were working on, perhaps as a field within the Builder class.Here's an outline for how the
StartConstructionmethod would look assuming theBuilderclass has a property or method calledGetCurrentBuilding()to access the building they are responsible for:private void StartConstruction(Builder builder) { // Retrieve the building the builder was last associated with. This assumes the Builder class has the method GetCurrentBuilding(). Building building = builder.GetCurrentBuilding(); // Check if the building still needs construction. if (building != null && building.GetConstructionProgress() < 100) { // The builder has resumed work, remove them from the available builders list and add them to the busy builders list. if (availableBuilders.Contains(builder)) { availableBuilders.Remove(builder); } if (!busyBuilders.Contains(builder)) { busyBuilders.Add(builder); } // Resume construction at the start of day. StartCoroutine(ConstructBuilding(builder, building)); } else { // If the building is completed or invalid, mark the builder as available again. builder.MarkAsAvailable(); availableBuilders.Add(builder); } }This method assumes each
Builderknows their currentBuildingto resume construction. When the day starts, you retrieve theBuildingand if it still needs construction, you resume the coroutine that was responsible for construction. If thebuildingis either completed ornull(which shouldn't happen normally, but might due to a destroyed building or other edge case), theBuilderis marked as available again.It's also critical to manage the
availableBuildersandbusyBuilderslists properly to avoid any builder being both available and busy at the same time, which could lead to errors in the logic. Additionally, thorough checks should be put in place throughout your system to maintain consistent state, especially when dealing with multithreading from coroutines and event-based systems like day/night cycles. - User
Any builder can continue any building I dont need a specific builder to continue a specific building
- Assistant
Given that any builder can continue the construction of any building, we can simplify the
StartConstructionmethod. Since the builders aren't tied to specific buildings, we don't need to track the relationship between a builder and a building when nighttime comes. Therefore, theStartConstructionmethod's main goal is to simply pick up the next available construction task from either thedestroyedQueueor theconstructionQueueat the start of the day.Here's the revised
StartConstructionmethod:private void StartConstruction() { // Resume construction at the start of day with available builders. while (availableBuilders.Count > 0) { // Check if there is a building that needs to be constructed or rebuilt. Building buildingToConstruct = null; if (destroyedQueue.Count > 0) { buildingToConstruct = destroyedQueue.Dequeue(); } else if (constructionQueue.Count > 0) { buildingToConstruct = constructionQueue.Dequeue(); } if (buildingToConstruct != null) { // We have a building to construct and an available builder. Builder builder = availableBuilders[0]; availableBuilders.RemoveAt(0); busyBuilders.Add(builder); builder.MarkAsBusy(); StartCoroutine(ConstructBuilding(builder, buildingToConstruct)); } else { // No buildings require construction at the moment. break; } } } private void DayAction() { isNightTime = false; // Resume construction for any buildings in the queue. StartConstruction(); }In this version,
StartConstructiondoes not need to take aBuilderas a parameter. Instead, it continues to take builders from theavailableBuilderslist and assigns them to the construction of buildings from the queues until there are no more suitable combinations of builders and buildings left. TheDayActionmethod simply changes theisNightTimeflag and callsStartConstructionto resume construction activities.Remember to mark builders as busy when they are selected to resume construction and add them to the
busyBuilderslist so they aren't considered available any longer. Additionally, make sure to remove them from thebusyBuildersand add them back to theavailableBuilderslist once they finish their construction tasks, or when they stop for nighttime (if such state management is necessary when implementing theNightAction).This simplified design ensures that any builder can continue any building without being tied to a specific building they were working on previously.
- User
Also I want you to handle these casse:
- The user can unassign a builder whenever he wants, I want you to remove a builder from the available builders, if that list is empty continue with the busy builders, if you remove a busy builder pause the activity he was doing and remove him
- Also I want you to check always if there are buldings to rebuild, if there are prioritize them if there are bulders available
- Assistant
To handle these additional cases, we'll need to modify the
BuilderManagerclass and provide methods to unassign builders and continuously prioritize rebuilding. Here's how it might look:public class BuilderManager : MonoBehaviour { // Existing members... // This method will be called by the user to unassign a builder. public void UnassignBuilder() { if (availableBuilders.Count > 0) { // Remove a builder from the available builders list. Builder builderToRemove = availableBuilders[0]; availableBuilders.RemoveAt(0); // Perform any necessary cleanup for the unassigned builder. builderToRemove.OnUnassigned(); } else if (busyBuilders.Count > 0) { // If no available builders, remove from busy builders. Builder builderToRemove = busyBuilders[0]; busyBuilders.RemoveAt(0); // If the builder was busy, pause their current activity. builderToRemove.PauseConstruction(); // Now the builder is neither available nor busy. builderToRemove.OnUnassigned(); } } void Update() { // Always check if there are buildings to rebuild and assign builders if available. PrioritizeRebuilding(); AssignBuildersToConstruction(); } private void PrioritizeRebuilding() { if (!isNightTime && availableBuilders.Count > 0 && destroyedQueue.Count > 0) { Building buildingToRebuild = destroyedQueue.Dequeue(); Builder builder = availableBuilders[0]; availableBuilders.RemoveAt(0); busyBuilders.Add(builder); builder.MarkAsBusy(); StartCoroutine(ConstructBuilding(builder, buildingToRebuild)); } } // Revised ConstructBuilding coroutine... // Revised DayAction method... // Revised NightAction method... // Rest of BuilderManager... } public class Builder { // Builder class members... // This method should be called when a builder is unassigned or interrupted. public void OnUnassigned() { // Implement any necessary logic when a builder is unassigned. // Example: Send the builder back to a waiting area or idle state. } // This method can be used to pause construction activities if a builder is unassigned while busy. public void PauseConstruction() { // Implement the logic to pause construction activities. // Example: Stop the corresponding construction coroutine. } // Rest of Builder class... }In this revised version, we've added the
UnassignBuildermethod, which the user can call to unassign a builder. If an available builder is present, one is simply removed from theavailableBuilderslist. If no available builder exists, we remove a busy builder, pause their activity, and handle their unassignment.The
Updatemethod now callsPrioritizeRebuildingeach frame beforeAssignBuildersToConstructionto ensure that rebuilding damaged structures is always given priority if necessary.Additionally, you will need to modify other methods like
AssignBuildersToConstructionandConstructBuildingto handle the state changes when a busy builder is unassigned. ThePauseConstructionmethod will likely stop the construction coroutine and set some state to indicate that the construction has been paused, but the specifics will depend on your coroutine implementation.Please note that this is a simplified version of the logic you may require. In a real strategy game, you should consider adding additional checks and balances to maintain consistency, like ensuring a builder is indeed busy before attempting to pause their activity, or updating any relevant UI elements when a builder status changes.
- User
Before starting the costruction the builder need to get to the building, when he is there then the constructions starts
- Assistant
To include the requirement that the builder needs to reach the building before starting construction, we can extend the
ConstructBuildingcoroutine to first handle the movement phase. This involves checking the distance between the builder and the building and using a movement method to approach the building target.Here's the updated
ConstructBuildingcoroutine with pseudo-code for movement:private IEnumerator ConstructBuilding(Builder builder, Building building) { // Move builder to the building first yield return StartCoroutine(MoveBuilderToBuilding(builder, building)); // If it's night time by the time the builder gets there, don't start construction. if (isNightTime) { yield break; } // Begin construction process builder.MarkAsBusy(); while (building.GetConstructionProgress() < 100 && !isNightTime) { building.Construct(); // Simulates the construction over time. yield return new WaitForSeconds(1f); // Wait time simulating construction work in progress. } // If completed during the day, mark building as complete and free up the builder if (building.GetConstructionProgress() >= 100) { building.MarkAsComplete(); builder.MarkAsAvailable(); busyBuilders.Remove(builder); availableBuilders.Add(builder); } } private IEnumerator MoveBuilderToBuilding(Builder builder, Building building) { float arrivalThreshold = 0.5f; // Threshold distance to consider the builder "arrived" while (Vector3.Distance(builder.transform.position, building.transform.position) > arrivalThreshold) { builder.MoveTowards(building.transform.position); // Implement this to move your builder towards the building yield return null; // Wait until next frame } // Builder has arrived; you could do a callback or event here if needed. builder.OnArrival(); }In this code:
- The
MoveBuilderToBuildingmethod is a coroutine that moves the builder towards the building until it's close enough (within anarrivalThresholddistance). You need to implement theMoveTowardsmethod within the Builder class to handle the actual movement logic, which could use pathfinding or simple straight-line movement depending on your game mechanics. - The
OnArrivalmethod should be implemented in the Builder class. It could handle the logic for what happens when a builder arrives at the construction site. This could be as simple as playing an animation or setting a flag indicating that the builder is ready to start work. - After the builder arrives at the building, the coroutine checks if it's night time. If it is, the coroutine ends early (using
yield break;). Otherwise, the construction process begins. - The actual construction is simulated by repeatedly calling the
Constructmethod on the Building object until its construction progress reaches 100%, or it becomes night time. The one-second wait (yield return new WaitForSeconds(1f);) is arbitrary and can be adjusted to suit your game's pacing.
Please remember to adjust the
DayActionandNightActionmethods accordingly to ensure they respect this new movement phase. You'll also need to pause the movement and construction process properly if the builder gets unassigned or it becomes night during the movement phase. - The
- User
No, the builder is a IA agent
- Assistant
As the builder is an AI agent, we would typically use a pathfinding system, such as Unity's NavMesh, to handle the movement towards the target building. Here's an updated version of the
ConstructBuildingcoroutine which assumes you're using Unity's Navigation system, though the actual movement code might vary depending on your specific AI implementation.using UnityEngine; using UnityEngine.AI; // ... other using directives private IEnumerator ConstructBuilding(Builder builder, Building building) { // First move the builder to the building using the NavMeshAgent. NavMeshAgent agent = builder.GetComponent<NavMeshAgent>(); agent.destination = building.transform.position; // Wait until the builder has arrived at the building. while (!builder.HasArrived()) { // Could add more complex checks here, like if the builder becomes stuck or the path is invalid. yield return null; // Wait until the next frame. } // Now that the builder has arrived, we can start the construction. if (isNightTime) { // If it's night time when the builder arrives, construction should not start. yield break; } builder.MarkAsBusy(); while (building.GetConstructionProgress() < 100 && !isNightTime) { building.Construct(); yield return new WaitForSeconds(1f); // Adjust as needed for your game's pacing. } if (building.GetConstructionProgress() >= 100) { building.MarkAsComplete(); } busyBuilders.Remove(builder); availableBuilders.Add(builder); builder.MarkAsAvailable(); } // Update the Builder class with the HasArrived method. public class Builder : MonoBehaviour { NavMeshAgent agent; void Awake() { agent = GetComponent<NavMeshAgent>(); } public bool HasArrived() { // Check if the path is complete and the agent is close enough to the target. return !agent.pathPending && agent.remainingDistance <= agent.stoppingDistance && !agent.hasPath; } // Other methods in the Builder class... }In this updated
ConstructBuildingcoroutine:- We'd start by setting the
NavMeshAgent's destination to the position of theBuilding. - The loop then uses the
HasArrivedmethod of theBuilderto check whether the agent has reached the destination. This method checks that the path is complete (!agent.pathPending), the remaining distance is within the stopping distance (agent.remainingDistance <= agent.stoppingDistance), and the agent doesn't have a path (!agent.hasPath), which typically indicates arrival. - Once the builder has arrived, we check if it's nighttime. If so, we exit the coroutine early (
yield break;). - If it's not nighttime, the builder is marked as busy, and the construction process begins.
- After the building is complete or if it turns nighttime, we perform cleanup by marking the builder as available and adjusting the available and busy builder lists.
Please ensure that
NavMeshAgentis correctly set up on all Builder AI agents, and the environment is correctly baked with NavMesh surfaces for pathfinding to work as expected. Unity's navigation system requires that your level geometry is appropriately set up with NavMesh areas where your agents can walk.Handling interruptions (such as the builder being unassigned) during the movement or construction phase will require additional logic to stop the
NavMeshAgentand cancel the coroutine if necessary. - We'd start by setting the
- User
The building has a building duration, how do I handle thath on this method
private IEnumerator ConstructBuilding(Builder builder, BuildingBase building) { // First move the builder to the building using the NavMeshAgent. IAstarAI agent = builder.Agent; builder.GoToBuilding(building.transform.position);
// Wait until the builder has arrived at the building. while (!agent.reachedEndOfPath) { yield return null; } // Now that the builder has arrived, we can start the construction. if (isNightTime) { // If it’s night time when the builder arrives, construction should not start. yield break; } builder.MarkAsBusy(true); while (building.GetConstructionProgress() < 100 && !isNightTime) { building.Construct(); yield return new WaitForSeconds(1f); // Adjust as needed for your game’s pacing. } if (building.GetConstructionProgress() >= 100) { building.MarkAsComplete(); } busyBuilders.Remove(builder); availableBuilders.Add(builder); builder.MarkAsAvailable(); } - Assistant
To handle the building duration within the
ConstructBuildingcoroutine, you'll want to integrate the duration concept into the construction logic. A building's construction duration is typically the total time it takes to complete the building from start to finish. You can simulate this process by incrementally increasing the construction progress over time according to the building's set duration.Here's an updated version of the
ConstructBuildingcoroutine that incorporates a building duration:private IEnumerator ConstructBuilding(Builder builder, BuildingBase building) { // First move the builder to the building using the navigation component. IAstarAI agent = builder.Agent; builder.GoToBuilding(building.transform.position); // Wait until the builder has arrived at the building. while (!agent.reachedEndOfPath) { yield return null; // Keep checking each frame. } // Now that the builder has arrived, we can start the construction. if (isNightTime) { // If it’s night time when the builder arrives, construction should not start. builder.MarkAsAvailable(); // Make sure the builder is marked available if construction can't start. yield break; } builder.MarkAsBusy(true); float buildTime = building.GetBuildDuration(); // Get the total duration required for building. float startTime = Time.time; // Record the start time. float progress = 0f; // Initialize progress. while (progress < 1f && !isNightTime) { float elapsedTime = Time.time - startTime; // Calculate elapsed time. progress = Mathf.Clamp01(elapsedTime / buildTime); // Calculate normalized progress (0 to 1). building.SetConstructionProgress(progress * 100); // Set the construction progress on the building (0 to 100). yield return null; // Wait until the next frame. } // If building progress has reached 100% (normalized progress == 1), mark it as complete. if (progress >= 1f) { building.MarkAsComplete(); } // Whether completed or interrupted by night time, mark the builder as available. busyBuilders.Remove(builder); availableBuilders.Add(builder); builder.MarkAsAvailable(); }The changes include:
- The
builder.GoToBuildingmethod initiates moving the builder to the building's position using the navigation system provided by your AI agent, which could be using A* Pathfinding Project or Unity NavMesh. Ensure thatbuilder.Agentrefers to your AI agent component and that it correctly moves the builder towards a given destination. - Once the builder reaches the building (
!agent.reachedEndOfPath), you check theisNightTimeflag. If it's night, cancel the construction by marking the builder as available and breaking the coroutine. - If it's day and the builder has arrived, construction starts. The coroutine calculates the construction progress based on the elapsed time compared to the predefined building duration (
GetBuildDurationmethod). - The
SetConstructionProgressmethod updates the building's construction progress. This method likely affects the visual display of the building's construction state (such as a progress bar or partially constructed appearance). - If construction is completed (
progress >= 1f), the building is marked as complete. Otherwise, if nighttime interrupts the process, the coroutine exits, and the progress will be paused until the next day. - Builders are properly managed in the
busyBuildersandavailableBuilderslists whenever they become available or busy.
Make sure that the
BuildingBaseclass has methodsGetBuildDuration,SetConstructionProgress, andMarkAsCompleteproperly implemented to reflect the building details and ensure progress visualization is handled accordingly. Also, ensure theisNightTimeflag is appropriately set according to your game's day-night cycle mechanism. - The
- User
I want you to create a method to pause the construction of a certain building
- Assistant
To create a method that allows you to pause the construction of a specific building, you can add functionality to the
BuildingBaseclass for managing the construction state, including a flag indicating whether the construction is paused. You will then modify the coroutine in theBuilderManagerto check for this flag.Here's what the updated code could look like:
public class BuildingBase : MonoBehaviour { // Other members of the BuildingBase class... private bool isConstructionPaused = false; public void PauseConstruction() { isConstructionPaused = true; } public void ResumeConstruction() { isConstructionPaused = false; } public bool IsConstructionPaused() { return isConstructionPaused; } // Rest of the BuildingBase class implementation... } public class BuilderManager : MonoBehaviour { // Other members of the BuilderManager class... private IEnumerator ConstructBuilding(Builder builder, BuildingBase building) { // Initial moving part stays the same... // Now that the builder has arrived, we can start the construction. if (isNightTime || building.IsConstructionPaused()) { builder.MarkAsAvailable(); yield break; } builder.MarkAsBusy(true); float buildTime = building.GetBuildDuration(); // Get the total duration required for building. float startTime = Time.time; // Record the start time. float progress = building.GetConstructionProgress() / 100f; // Get current progress and convert to 0-1 range as needed. while (progress < 1f && !isNightTime && !building.IsConstructionPaused()) { float elapsedTime = Time.time - startTime; // Update elapsed time. progress = Mathf.Clamp01(elapsedTime / buildTime); // Calculate normalized progress (0 to 1). building.SetConstructionProgress(progress * 100); // Update the construction progress on the building. yield return null; // Wait until the next frame. } if (progress >= 1f && !building.IsConstructionPaused()) { building.MarkAsComplete(); } busyBuilders.Remove(builder); availableBuilders.Add(builder); builder.MarkAsAvailable(); } // Rest of the BuilderManager implementation... }This code introduces the following changes:
- Adds a
boolfieldisConstructionPausedto yourBuildingBaseclass to track the construction's pause state. - Provides
PauseConstruction,ResumeConstruction, andIsConstructionPausedmethods inBuildingBaseto manage that state. - Updates the coroutine
ConstructBuildingin theBuilderManagerclass to handle the pause condition correctly. The coroutine now includes a check forbuilding.IsConstructionPaused()in its loop condition and immediately exits if the construction is paused. - Calling
BuildingBase.PauseConstructionwould set the flag to true, causing the coroutine to bypass the construction loop and exit on the next iteration. Correspondingly, callingBuildingBase.ResumeConstructionwould allow the coroutine to resume construction by clearing the pause flag.
Note that you would have to handle the resumption of the construction somewhere in your game logic; this could involve restarting the coroutine when the pause condition is changed, provided that you manage the state of your builders and buildings correctly. You'll also have to take care that multiple coroutines for the same building are not running concurrently.
- Adds a
- User
And how do I resume a paused building giving as parameters Builder builder, Building Base building, I suppose he have to stop the last coroutine and start a new one
- Assistant
To resume a paused building, you should indeed stop the corresponding coroutine if it's still running and start a new one. This is necessary because the progress of construction should pick up from where it was paused. You'll want to track the coroutines so that you can stop them as needed. One way to do this is by using a
Coroutinehandle.Here's how you could implement this behavior:
public class BuilderManager : MonoBehaviour { private Dictionary<BuildingBase, Coroutine> constructionCoroutines = new Dictionary<BuildingBase, Coroutine>(); // Other members of the BuilderManager class... // Call this method to resume construction with a specific builder on a specific building. public void ResumeConstruction(Builder builder, BuildingBase building) { // First, check if there already is a coroutine for this building and stop it if necessary if (constructionCoroutines.TryGetValue(building, out Coroutine ongoingCoroutine)) { if (ongoingCoroutine != null) { StopCoroutine(ongoingCoroutine); } constructionCoroutines[building] = null; } // Resume construction by starting a new coroutine and storing the reference in the dictionary Coroutine newCoroutine = StartCoroutine(ConstructBuilding(builder, building)); constructionCoroutines[building] = newCoroutine; } private IEnumerator ConstructBuilding(Builder builder, BuildingBase building) { // Move builder to the building first... // Wait until the builder has arrived at the building... // Check for night time or pause status before construction if (isNightTime || building.IsConstructionPaused()) { yield break; } builder.MarkAsBusy(true); building.ResumeConstruction(); // Clears the paused flag on the building float buildTime = building.GetBuildDuration(); // Get the total duration required for building. float startTime = Time.time - (building.GetConstructionProgress() / 100f) * buildTime; // Adjust start time based on current progress. float progress = building.GetConstructionProgress() / 100f; // Get current progress in the range of 0-1. while (progress < 1f && !isNightTime && !building.IsConstructionPaused()) { float elapsedTime = Time.time - startTime; // Calculate elapsed time. progress = Mathf.Clamp01(elapsedTime / buildTime); // Calculate normalized progress (0 to 1). building.SetConstructionProgress(progress * 100); // Set the construction progress on the building. yield return null; // Wait until the next frame. } if (progress >= 1f) { building.MarkAsComplete(); } // Cleanup busyBuilders.Remove(builder); availableBuilders.Add(builder); builder.MarkAsAvailable(); // Remove the coroutine from the tracking dictionary as it's finished if (constructionCoroutines.ContainsKey(building)) { constructionCoroutines[building] = null; } } // Rest of the BuilderManager implementation... } public class BuildingBase : MonoBehaviour { //... Rest of the BuildingBase class... public float GetBuildDuration() { // Needs implementation: return the duration required to build this building. } public void SetConstructionProgress(float progress) { // Needs implementation: update the building's visual progress indicator. } public float GetConstructionProgress() { // Needs implementation: return the current construction progress. } //... Other methods... }With these changes, when you call
ResumeConstruction, it will:- Check if there is an ongoing coroutine for the building.
- Stop the existing coroutine, if any.
- Start a new coroutine to handle construction.
- Store the reference to the new coroutine in
constructionCoroutines.
The
ConstructBuildingcoroutine:- Resumes from the current construction progress rather than starting over.
- Updates construction progress based on the elapsed time since construction began, including any previous work before a pause, if any.
- Manages the tracking of the coroutine in
constructionCoroutines. - Sets the construction progress which should influence the building display (like partially built models or a loading bar).
Also, note that in a real-world application, you might want to handle edge cases more robustly, such as ensuring you don't resume construction during nighttime or handling multiple resume calls in quick succession.
- User
Is it not better stop the corountine after realizing the cosntruction is pause, so you dont have to create the dictionary
- Assistant
Yes, you're absolutely right. Stopping the coroutine when the construction is paused is a more efficient and cleaner approach compared to tracking coroutines in a dictionary. Since each builder should only be working on one construction task at a time, you can directly manage the coroutine within the builder itself.
First, you'll need to add functionality to the
Builderclass to keep track of the coroutine that's handling the construction process.Here's an updated version of the
BuilderandBuilderManagerclasses implementing this strategy:public class Builder : MonoBehaviour { // Previously existing members... private Coroutine currentConstructionCoroutine; public void StartConstruction(BuildingBase building) { if (currentConstructionCoroutine != null) { StopConstruction(); } currentConstructionCoroutine = StartCoroutine(BuildingManager.Instance.ConstructBuilding(this, building)); } public void StopConstruction() { if (currentConstructionCoroutine != null) { StopCoroutine(currentConstructionCoroutine); currentConstructionCoroutine = null; } } // Existing methods like HasArrived, OnUnassigned, and so on... } public class BuilderManager : MonoBehaviour { // Other members of the BuilderManager class... public IEnumerator ConstructBuilding(Builder builder, BuildingBase building) { // Move builder to the building first... // Wait until the builder has arrived at the building... // Now start the construction process or resume from a pause builder.MarkAsBusy(true); building.ResumeConstruction(); // Make sure the paused flag is cleared float buildTime = building.GetBuildDuration(); float elapsedTime = building.GetConstructionProgress() / 100f * buildTime; while (building.GetConstructionProgress() < 100 && !isNightTime && !building.IsConstructionPaused()) { elapsedTime += Time.deltaTime; // Add to elapsed time each frame float progress = Mathf.Clamp01(elapsedTime / buildTime); building.SetConstructionProgress(progress * 100); yield return null; // Wait until next frame } if (building.GetConstructionProgress() >= 100) { building.MarkAsComplete(); } // Cleanup busyBuilders.Remove(builder); availableBuilders.Add(builder); builder.MarkAsAvailable(); builder.StopConstruction(); // Clear the currentConstructionCoroutine field } // Method to pause construction on a specific building public void PauseBuildingConstruction(BuildingBase building) { // Find the builder that is currently working on this building Builder builderWorkingOnBuilding = busyBuilders.FirstOrDefault(b => b.CurrentBuilding == building); if (builderWorkingOnBuilding != null) { builderWorkingOnBuilding.StopConstruction(); } building.PauseConstruction(); } // Rest of the BuilderManager implementation... }In this implementation:
- The
Builderclass has been updated with methodsStartConstructionandStopConstructionto start and stop the construction coroutine. - The
BuilderManagerclass's coroutineConstructBuildingno longer requires a dictionary to track coroutines, as eachBuildernow tracks its own. - A new method,
PauseBuildingConstruction, has been added toBuilderManagerto pause construction on a given building. It looks for the builder currently working on that building and uses the builder'sStopConstructionmethod to end the coroutine. - Upon completion of the coroutine (either when construction finishes or is pre-emptively stopped), the current construction coroutine is cleared from the
currentConstructionCoroutinefield of theBuilder.
Now, when the construction of a building needs to be paused, you simply call
PauseBuildingConstruction(building)method onBuilderManagerwhich will take care of stopping the coroutine. When you want to resume construction, you'll use the builder'sStartConstruction(building)method to begin a new coroutine.This approach is more modular and avoids the complexity and overhead of managing a dictionary of coroutines. Each builder is responsible for its construction task, and coroutines are started and stopped directly within the builder objects.
- The
- User
I want you to take into account that the initial progress maybe is not 0 because the building has some progress/health already
private IEnumerator ConstructBuilding(Builder builder, BuildingBase building) { // First move the builder to the building using the navigation component. IAstarAI agent = builder.Agent; builder.GoToBuilding(building.transform.position);
// Wait until the builder has arrived at the building. while (agent.pathPending || !agent.reachedEndOfPath) { yield return null; // Keep checking each frame. } // Now that the builder has arrived, we can start the construction. if (isNightTime) { // If it’s night time when the builder arrives, construction should not start. builder.MarkAsBusy(false); // Make sure the builder is marked available if construction can’t start. yield break; } builder.MarkAsBusy(true); float buildTime = building.GetBuildDuration(); // Get the total duration required for building. float startTime = Time.time; // Record the start time. float progress = 0f; // Initialize progress. builder.SetBuilding(building); builder.SetState(UnitBase.CharacterState.Working); Vector3 targetDirection = new Vector3(building.boundsCollider.transform.position.x, transform.position.y, building.boundsCollider.transform.position.z) - builder.transform.position; // Create the rotation we need to be in to look at the target Quaternion targetRotation = Quaternion.LookRotation(targetDirection.normalized); while (progress < 1f && !isNightTime) { if (building.IsConstructionPaused()) { pendingBuildingQueue.Enqueue(building); yield break; } builder.transform.rotation = Quaternion.Slerp(builder.transform.rotation, targetRotation, Time.deltaTime * 10); float elapsedTime = Time.time - startTime; // Calculate elapsed time. progress = Mathf.Clamp01(elapsedTime / buildTime); // Calculate normalized progress (0 to 1). building.SetConstructionProgress(progress); // Set the construction progress on the building (0 to 100). yield return null; // Wait until the next frame. } // If building progress has reached 100% (normalized progress == 1), mark it as complete. if (progress >= 1f) { building.MarkAsComplete(); builder.SetState(UnitBase.CharacterState.Idle); } // Whether completed or interrupted by night time, mark the builder as available. busyBuilders.Remove(builder); availableBuilders.Add(builder); builder.MarkAsBusy(false); } - Assistant
To account for a building that already has some initial progress (or health), you will need to ensure the coroutine starts construction progress from the current state of the building rather than beginning at zero.
A
BuildingBaseclass should have a method to get the current progress as a percentage. This percentage can be used to calculate both the starting progress and the time elapsed since the start of construction. Here is how you might adjust the coroutine to account for existing progress:private IEnumerator ConstructBuilding(Builder builder, BuildingBase building) { IAstarAI agent = builder.Agent; builder.GoToBuilding(building.transform.position); // Wait until the builder has arrived at the building. while (agent.pathPending || !agent.reachedEndOfPath) { yield return null; // Keep checking each frame. } if (isNightTime) { builder.MarkAsBusy(false); // Make sure the builder is marked available if construction can’t start. yield break; } builder.MarkAsBusy(true); builder.SetBuilding(building); builder.SetState(UnitBase.CharacterState.Working); // Look at the building. Vector3 targetDirection = new Vector3(building.boundsCollider.transform.position.x, transform.position.y, building.boundsCollider.transform.position.z) - builder.transform.position; Quaternion targetRotation = Quaternion.LookRotation(targetDirection.normalized); // Get existing progress and calculate elapsed time based on it. float buildTime = building.GetBuildDuration(); float initialProgress = building.GetConstructionProgress(); // Get the initial progress in the range 0-1. float elapsedTime = initialProgress * buildTime; // Convert back to time. float progress = initialProgress; while (progress < 1f && !isNightTime) { if (building.IsConstructionPaused()) { pendingBuildingQueue.Enqueue(building); builder.SetState(UnitBase.CharacterState.Idle); builder.MarkAsBusy(false); yield break; } // Slerp rotation to look at the building. builder.transform.rotation = Quaternion.Slerp(builder.transform.rotation, targetRotation, Time.deltaTime * 10); // Advance progress. elapsedTime += Time.deltaTime; // Add to elapsed time each frame. progress = Mathf.Clamp01(elapsedTime / buildTime); // Calculate normalized progress (0 to 1). building.SetConstructionProgress(progress); // Set the construction progress on the building (0 to 1). yield return null; // Wait until the next frame. } if (progress >= 1f) { building.MarkAsComplete(); builder.SetState(UnitBase.CharacterState.Idle); } // Cleanup busyBuilders.Remove(builder); availableBuilders.Add(builder); builder.MarkAsBusy(false); }In this updated coroutine:
- We retrieve the initial construction progress from
building.GetConstructionProgress(), which should return a value between 0 and 1 representing the percentage of completion. - The
elapsedTimevariable is then set by multiplying the initial progress by the total build time, effectively giving us a starting point for the elapsed time. - The while loop now increments
elapsedTimebyTime.deltaTimeeach frame, which, when divided by thebuildTime, gives us an updated progress percentage that correctly accounts for the initial progress. - The coroutine still monitors the
isNightTimeflag and theIsConstructionPaused()state, behaving appropriately if either event occurs.
Make sure that
building.GetConstructionProgress()provides the current construction progress value normalized to the range of 0 to 1, andbuilding.SetConstructionProgress(progress)accepts a normalized value. Ifbuilding.SetConstructionProgress(progress)instead takes a value from 0 to 100, adjust the parameter passed to that method accordingly. Additionally, theMarkAsBusy()method should clearly indicate the builder's busy state. - We retrieve the initial construction progress from