I want you to improve this script, complete the night action, each village should move to the closest house according to villasger position, but each house has a stablished villagerCapacity, if house is full search for next closest house to the villager, associate the house with the villager in a dictionary
using System;
using System.Collections.Generic;
using Game.Systems.Buildings;
using UnityEngine;
namespace Game.Systems
{
public class HousingManager : MonoBehaviour
{
private List houses = new List();
To improve the script and implement the night action logic, I'll add a method called AssignHousesToVillagers() to find the best house for each villager based on their proximity and the house's capacity. This method will sort the houses by distance from each villager and assign the villager to the closest available house. If a house is full, it will select the next closest house with available capacity.
Here's the updated script with comments explaining the changes:
csharp
User
If there is no house available, got to the castle
using System;
using System.Collections.Generic;
using System.Linq; // Added to use LINQ for sorting
using Game.Systems.Buildings;
using UnityEngine;
namespace Game.Systems
{
public class HousingManager : MonoBehaviour
{
[SerializeField] private Castle castle;
private List houses = new List();
// Added a dictionary to associate villagers with houses
private Dictionary<Villager, House> villagerToHouseMap = new Dictionary<Villager, House>();
code
public void Init()
{
GameManager.Instance.OnDayStart += DayAction;
GameManager.Instance.OnNightStart += NightAction;
}
public void DayAction(object sender, EventArgs args)
{
// Reset villager to house associations for the next night.
villagerToHouseMap.Clear();
}
public void NightAction(object sender, EventArgs args)
{
List<Villager> villagers = GameManager.Instance.VillagerTracker.GetVillagers();
AssignHousesToVillagers(villagers);
}
private void AssignHousesToVillagers(List<Villager> villagers)
{
foreach (var villager in villagers)
{
// Sort houses by distance to the villager
var sortedHouses = houses.OrderBy(house => Vector3.Distance(villager.transform.position, house.transform.position)).ToList();
foreach (var house in sortedHouses)
{
// Check if the current house has available capacity
if (house.VillagerCapacity > house.CurrentOccupants)
{
// Assign the villager to the house and update the house’s current occupants
house.CurrentOccupants++;
villagerToHouseMap[villager] = house;
villager.MoveToPosition(house.gatheringPoint.position);
break; // Break out of the loop once a house is assigned
}
}
}
}
public void AddHouse(House house)
{
if (!houses.Contains(house))
{
houses.Add(house);
}
}
public void RemoveHouse(House house)
{
if (houses.Contains(house))
{
houses.Remove(house);
}
}
// Method added to get the house assigned to a particular villager.
public House GetHouseForVillager(Villager villager)
{
return villagerToHouseMap.TryGetValue(villager, out House house) ? house : null;
}
private void OnDestroy()
{
GameManager.Instance.OnDayStart -= DayAction;
GameManager.Instance.OnNightStart -= NightAction;
}
}
Assistant
In the provided script structure, we will handle the case where if there are no available houses with enough capacity, the villagers will move to the castle. You have a Castle class, which I'll assume is similar to the House class but it doesn't have a limit on the number of villagers it can host.
I will also add the logic to actually move the villager to the castle if no house is available, assuming Villager has a method MoveToPosition which accepts a Transform as an argument and instructs the villager to move to that position.
Here's how we can extend the script to implement this functionality:
csharp
using System; // ...
using UnityEngine; // ...
// ... other using directives
namespace Game.Systems
{
public class HousingManager : MonoBehaviour
{
[SerializeField] private Castle castle; // Reference to the Castle object
// ... other fields
// ... Init, DayAction, AddHouse, RemoveHouse, GetHouseForVillager, OnDestroy as before
private void AssignHousesToVillagers(List<Villager> villagers)
{
foreach (var villager in villagers)
{
bool assignedHouse = false;
// Sort houses by distance to the villager
var sortedHouses = houses.OrderBy(house => Vector3.Distance(villager.transform.position, house.transform.position)).ToList();
foreach (var house in sortedHouses)
{
// Check if the current house has available capacity
if (house.VillagerCapacity > house.CurrentOccupants)
{
// Assign the villager to the house and update the house's current occupants
house.CurrentOccupants++;
villagerToHouseMap[villager] = house;
villager.MoveToPosition(house.gatheringPoint.position); // assuming house.gatheringPoint refers to a Transform.
assignedHouse = true;
break; // Break out of the loop once a house is assigned
}
}
// If no house is available, go to the castle
if (!assignedHouse)
{
villager.MoveToPosition(castle.gatheringPoint.position); // assuming castle.gatheringPoint refers to a Transform.
}
}
}
// ... rest of the script remains unchanged
}
}
User
In movetohouse start a corountine, if villager reachesendofpath or some fixed time has passed then set gameobject active = false
using System.Collections;
using Game.ImprovedAI;
using Pathfinding;
using UnityEngine;
namespace Game.Systems.Buildings
{
public class Villager : MonoBehaviour
{
[SerializeField] protected GameObject body;
code
public IAstarAI Agent;
protected AnimationStateController animationController;
public void Init()
{
Agent = GetComponent<IAstarAI>();
animationController = GetComponent<AnimationStateController>();
GameManager.Instance.VillagerTracker.AddVillager(this);
}
public void MoveToHouse(Vector3 position)
{
Agent.destination = position;
Agent.SearchPath();
animationController.SetAnimation(UnitBase.CharacterState.Walking);
}
public void DisableVillager()
{
GameManager.Instance.VillagerTracker.RemoveVillager(this);
GameManager.Instance.StatsManager.CurrentVillagers--;
}
public void DestroyVillager()
{
Destroy(this.gameObject);
}
}
}
Assistant
To implement the behavior where a villager moves to a house and becomes inactive after either reaching the end of the path or when a fixed time has passed, you will need to utilize coroutines in Unity. This allows for asynchronous behavior that can wait for certain conditions to be met or for a certain amount of time to elapse.
Below is an updated Villager script with the additional coroutine method called MoveToHouseAndDeactivate. This coroutine will monitor the villager's progress towards the house and will deactivate the villager's body GameObject after the given conditions are met.
csharp
User
How do i stablish a random position around a point
Assistant
To establish a random position around a specific point in Unity, you can use the Random.insideUnitCircle or Random.insideUnitSphere method depending on whether you want a random position in 2D or 3D. These methods return a point inside a circle or a sphere with a radius of 1 unit. You can scale the result by the desired radius to spread the area in which you want to generate the random position and then add that to the initial point.
Here's an example of how you can generate a random position around a point:
For 3D (You have to specify which plane you want to use. Here, I'm using the XZ plane):
csharp
Vector3 GetRandomPosition3D(Vector3 center, float radius)
{
Vector2 randomCircle = Random.insideUnitCircle * radius;
Vector3 randomPosition = new Vector3(randomCircle.x, 0, randomCircle.y) + center;
randomPosition.y = center.y; // Assuming you want to keep the Y position constant (ground level)
return randomPosition;
}
Here's how you can use these functions in your code. Assuming transform.position is the point around which you want to find a random position with a radius of 5 units:
For 2D:
csharp
Vector2 center = new Vector2(transform.position.x, transform.position.y);
Vector2 randomPos = GetRandomPosition2D(center, 5f);
For 3D:
csharp
Vector3 center = transform.position; // The point around which you want a random position
Vector3 randomPos = GetRandomPosition3D(center, 5f);
Depending on your game and how you're defining interactions, you may need to use a different plane or account for other factors, but this is the general approach to get a random position around a point.
User
Hi
Assistant
Hello! How can I assist you today? If you have any questions or need help with something, feel free to ask.
User
I want you to associate the house with its villagers, Liske a list of houses that have a list of villagers, propose something good
using System;
using System.Collections.Generic;
using System.Linq; // Added to use LINQ for sorting
using Game.Systems.Buildings;
using UnityEngine;
using Random = UnityEngine.Random;
namespace Game.Systems
{
public class HousingManager : MonoBehaviour
{
[SerializeField] private Castle castle;
private List houses = new List();
// Added a dictionary to associate villagers with houses
private Dictionary<Villager, House> villagerToHouseMap = new Dictionary<Villager, House>();
code
Assistant
To associate each house with its villagers, you can create a data structure that allows each House object to keep track of its own list of villagers. Here's how you could modify the House class to include a List<Villager> to hold its occupants, and then update the HousingManager to work with this:
Firstly, update the House class to include a list of villagers as its occupants:
csharp
namespace Game.Systems.Buildings
{
public class House : MonoBehaviour
{
// Existing House fields...
public int VillagerCapacity; // Assumes a field like this exists
private List<Villager> occupants = new List<Villager>();
public IReadOnlyList<Villager> Occupants => occupants; // ReadOnly access to outside
public int CurrentOccupants => occupants.Count;
// ... Other House methods and properties
public bool AddOccupant(Villager villager)
{
if (occupants.Count < VillagerCapacity)
{
occupants.Add(villager);
return true;
}
return false;
}
public void RemoveOccupant(Villager villager)
{
occupants.Remove(villager);
}
public void ClearOccupants()
{
occupants.Clear();
}
}
}
Then, update the HousingManager accordingly. Specifically, you'll no longer need the villagerToHouseMap because each house will maintain its own list of villagers. You'll also need to update the logic inside AssignHousesToVillagers to add villagers to houses' occupants lists:
csharp
User
Random rotation in y axis
Assistant
In Unity, to set a random rotation around the Y-axis for a GameObject, you can simply use the UnityEngine.Random.Range method to generate a random angle and then apply it to the GameObject's transform. This can be particularly useful when you want an object to face a random direction, such as when instantiating items or characters in a game world.
Here's how it can be done:
csharp
using UnityEngine;
public class RandomYRotation : MonoBehaviour
{
void Start()
{
SetRandomYRotation();
}
void SetRandomYRotation()
{
float randomYAngle = Random.Range(0f, 360f); // Random angle between 0 and 360 degrees
transform.rotation = Quaternion.Euler(0f, randomYAngle, 0f); // Apply rotation only on Y axis
}
}
This script, when attached to a GameObject, will set a random rotation around the Y-axis for that GameObject when the Start method is called. Here's the breakdown of what it does:
Random.Range(0f, 360f) generates a random float number between 0 and 360, representing degrees of rotation around the Y-axis.
transform.rotation accesses the rotation property of the GameObject's Transform component.
Quaternion.Euler(0f, randomYAngle, 0f) creates a rotation based on an Euler angle, with the Y component set to our random angle and the X and Z components set to 0 so that the rotation is only around the Y-axis.
You can call the SetRandomYRotation method at any point in your code where you need to set a random Y-axis rotation, for example, every time you instantiate a new GameObject.
User
How to fade an object on Unity, I have an opaque material and a tranparent material
Assistant
Fading an object in Unity from an opaque material to a transparent material can be achieved by switching materials and using Unity's built-in animation system or by adjusting material properties through code.
For this response, I'll show you a code-based approach that tweaks the alpha value of the material's color. To use this code, your material should be using a shader that supports transparency (e.g., Standard Shader with the rendering mode set to "Transparent").
Here's a simple script to gradually fade an object from opaque to transparent:
csharp
using UnityEngine;
public class FadeObject : MonoBehaviour
{
public Material opaqueMaterial;
public Material transparentMaterial;
// Time it takes to fade the material
public float fadeDuration = 2f;
private MeshRenderer meshRenderer;
private float fadeElapsed = 0f;
private bool isFading = false;
void Start()
{
// Get the MeshRenderer component attached to the object
meshRenderer = GetComponent<MeshRenderer>();
// Start with the opaque material
meshRenderer.material = opaqueMaterial;
}
public void StartFade()
{
if (isFading)
return; // Don't restart fade if already in progress
// Start fading the material
isFading = true;
fadeElapsed = 0f;
// Ensure transparent material is in the correct initial state
Color color = transparentMaterial.color;
color.a = 1f; // Opaque
transparentMaterial.color = color;
StartCoroutine(FadeToTransparent());
}
private IEnumerator FadeToTransparent()
{
while (fadeElapsed < fadeDuration)
{
// Calculate new alpha value based on elapsed fade time
float newAlpha = Mathf.Lerp(1f, 0f, fadeElapsed / fadeDuration);
Color color = meshRenderer.material.color;
color.a = newAlpha;
meshRenderer.material.color = color;
// Wait for the next frame
yield return null;
// Increment the elapsed fade time
fadeElapsed += Time.deltaTime;
}
// Set to the transparent material
meshRenderer.material = transparentMaterial;
isFading = false;
}
}
using System;
using System.Collections.Generic;
using System.Linq; // Added to use LINQ for sorting
using Game.Systems.Buildings;
using UnityEngine;
namespace Game.Systems
{
public class HousingManager : MonoBehaviour
{
private List<House> houses = new List<House>();
// Added a dictionary to associate villagers with houses
private Dictionary<Villager, House> villagerToHouseMap = new Dictionary<Villager, House>();
public void Init()
{
GameManager.Instance.OnDayStart += DayAction;
GameManager.Instance.OnNightStart += NightAction;
}
public void DayAction(object sender, EventArgs args)
{
// Reset villager to house associations for the next night.
villagerToHouseMap.Clear();
}
public void NightAction(object sender, EventArgs args)
{
List<Villager> villagers = GameManager.Instance.VillagerTracker.GetVillagers();
AssignHousesToVillagers(villagers);
}
private void AssignHousesToVillagers(List<Villager> villagers)
{
foreach (var villager in villagers)
{
// Sort houses by distance to the villager
var sortedHouses = houses.OrderBy(house => Vector3.Distance(villager.transform.position, house.transform.position)).ToList();
foreach (var house in sortedHouses)
{
// Check if the current house has available capacity
if (house.VillagerCapacity > house.CurrentOccupants)
{
// Assign the villager to the house and update the house's current occupants
house.CurrentOccupants++;
villagerToHouseMap[villager] = house;
break; // Break out of the loop once a house is assigned
}
}
}
}
public void AddHouse(House house)
{
if (!houses.Contains(house))
{
houses.Add(house);
}
}
public void RemoveHouse(House house)
{
if (houses.Contains(house))
{
houses.Remove(house);
}
}
// Method added to get the house assigned to a particular villager.
public House GetHouseForVillager(Villager villager)
{
return villagerToHouseMap.TryGetValue(villager, out House house) ? house : null;
}
private void OnDestroy()
{
GameManager.Instance.OnDayStart -= DayAction;
GameManager.Instance.OnNightStart -= NightAction;
}
}
}
Note that I added a method called GetHouseForVillager() to retrieve the house assigned to a specific villager. This can be useful if you need to access this information from other parts of your game.
Additionally, I've assumed that the House class has properties VillagerCapacity and CurrentOccupants which represent the maximum number of villagers the house can accommodate and the current number of villagers occupying the house, respectively. If this is not the case, you will need to add these properties to the House class.
This updated script should now correctly assign each villager to the closest available house at night and reset the associations each day.
}
In this updated AssignHousesToVillagers method, I've added a bool assignedHouse flag to determine whether the villager has been assigned to a house. If, after iterating through the sorted list of houses, no house can take the villager (!assignedHouse), then we command the villager to go to the castle's gathering point by calling villager.MoveToPosition(castle.gatheringPoint.position).
Make sure that the Castle class also has gatheringPoint, which represents the position where villagers should gather. If it doesn't, or if you need to implement a different logic for castle-gathering, make the necessary adjustments.
using System.Collections; // Necessary for coroutines
using Game.ImprovedAI;
using Pathfinding;
using UnityEngine;
namespace Game.Systems.Buildings
{
public class Villager : MonoBehaviour
{
[SerializeField] protected GameObject body; // Presumably the visual representation of the villager
public IAstarAI Agent;
protected AnimationStateController animationController;
// Use a bool to keep track of whether the villager is moving to a house
private bool isMovingToHouse = false;
private Coroutine moveToHouseCoroutine;
// A property to control the coroutine externally, if needed
public bool IsMovingToHouse
{
get { return isMovingToHouse; }
}
public void Init()
{
// ... (Initialization code remains the same)
}
// Updated method that starts the coroutine to move to a house and then deactivate
public void MoveToHouse(Vector3 position)
{
// Stop any existing move-to-house coroutine in case this method is called again for the same villager
if (moveToHouseCoroutine != null)
{
StopCoroutine(moveToHouseCoroutine);
}
// Set destination and start moving
Agent.destination = position;
Agent.SearchPath();
animationController.SetAnimation(UnitBase.CharacterState.Walking);
// Start the coroutine that will handle deactivation
moveToHouseCoroutine = StartCoroutine(MoveToHouseAndDeactivate());
}
private IEnumerator MoveToHouseAndDeactivate()
{
isMovingToHouse = true; // Now we're in the process of moving to the house.
// Wait for either the villager to reach the end of the path or for the timeout (e.g. 30 seconds)
float maxTime = 30f; // Timeout in seconds (set to whatever you consider appropriate)
float timeElapsed = 0f;
while (!Agent.reachedEndOfPath && timeElapsed < maxTime)
{
yield return null; // Wait until next frame
timeElapsed += Time.deltaTime; // Increment the timer
}
// The villager has either reached the destination or timed out
body.SetActive(false); // Deactivate the visual representation of the villager
// Call any other cleanup or state management functions needed when the villager "enters" the house
DisableVillager(); // You might want to rename or update this method depending on game logic.
isMovingToHouse = false; // We're no longer moving to the house.
}
public void DisableVillager()
{
// ... (Existing disable logic)
}
public void DestroyVillager()
{
Destroy(this.gameObject);
}
}
}
The MoveToHouseAndDeactivate coroutine checks regularly to see if either the Agent.reachedEndOfPath is true (meaning the villager has reached the house) or if maxTime seconds have passed. When either condition is met, the villager's body object is deactivated by setting SetActive(false).
Make sure to call the MoveToHouse method when you want the villager to move to the house and subsequently deactivate. Keep in mind that the disable logic might vary depending on your game, so you might need to adjust the DisableVillager method to align with your game's rules and state management.
public void Init()
{
GameManager.Instance.OnDayStart += DayAction;
GameManager.Instance.OnNightStart += NightAction;
}
public void DayAction(object sender, EventArgs args)
{
foreach (var villager in GameManager.Instance.VillagerTracker.GetVillagers())
{
villager.RestoreVillager();
}
}
public void NightAction(object sender, EventArgs args)
{
List<Villager> villagers = GameManager.Instance.VillagerTracker.GetVillagers();
AssignHousesToVillagers(villagers);
}
private void AssignHousesToVillagers(List<Villager> villagers)
{
foreach (var villager in villagers)
{
bool assignedHouse = false;
// Sort houses by distance to the villager
var sortedHouses = houses.OrderBy(house => Vector3.Distance(villager.transform.position, house.transform.position)).ToList();
foreach (var house in sortedHouses)
{
// Check if the current house has available capacity
if (house.VillagerCapacity > house.CurrentOccupants)
{
// Assign the villager to the house and update the house’s current occupants
house.CurrentOccupants++;
villagerToHouseMap[villager] = house;
villager.MoveToHouse(house.gatheringPoint.position);
assignedHouse = true;
break; // Break out of the loop once a house is assigned
}
}
// If no house is available, go to the castle
if (!assignedHouse)
{
villager.MoveToHouse(castle.gatheringPoint.position); // assuming castle.gatheringPoint refers to a Transform.
}
}
}
public void AddHouse(House house)
{
if (!houses.Contains(house))
{
houses.Add(house);
}
}
public void RemoveHouse(House house)
{
if (houses.Contains(house))
{
houses.Remove(house);
}
}
// Method added to get the house assigned to a particular villager.
public House GetHouseForVillager(Villager villager)
{
return villagerToHouseMap.TryGetValue(villager, out House house) ? house : null;
}
private void OnDestroy()
{
GameManager.Instance.OnDayStart -= DayAction;
GameManager.Instance.OnNightStart -= NightAction;
}
}
}
// ... Other using directives
namespace Game.Systems
{
public class HousingManager : MonoBehaviour
{
[SerializeField] private Castle castle;
private List<House> houses = new List<House>();
// ... Init, DayAction (without clearing the villagerToHouseMap)
private void AssignHousesToVillagers(List<Villager> villagers)
{
foreach (var villager in villagers)
{
bool assignedHouse = false;
var sortedHouses = houses.OrderBy(house => Vector3.Distance(villager.transform.position, house.transform.position)).ToList();
foreach (var house in sortedHouses)
{
if (house.AddOccupant(villager)) // AddOccupant now returns a bool
{
villager.MoveToHouse(house.gatheringPoint.position);
assignedHouse = true;
break;
}
}
if (!assignedHouse)
{
villager.MoveToHouse(castle.gatheringPoint.position); // Move to the castle if no house is available
}
}
}
// ... AddHouse, RemoveHouse
// New method to get the list of villagers in a house
public IReadOnlyList<Villager> GetOccupantsOfHouse(House house)
{
return house.Occupants;
}
// This method is no longer necessary, because `RemoveHouse` should already take care of this
/*
public void ClearOccupantsForHouse(House house)
{
house.ClearOccupants();
}
*/
// ... OnDestroy
// ... Rest of the script
}
}
Now, each House object manages its own list of villager occupants, which makes it straightforward to access the villagers from each house through House.Occupants. The HousingManager doesn't need to keep a separate map of this relationship.
Keep in mind that this assumes the existence of certain properties and methods you would need to implement in the House class (AddOccupant, RemoveOccupant, ClearOccupants, etc.) and assumes that the MoveToHouse method exists on the Villager class, as shown in your original snippet. Adjust the code as necessary to fit the actual structure of your game objects and classes.
Attach the script to the GameObject you want to fade. Make sure to set the opaqueMaterial and transparentMaterial fields in the Inspector to reference the appropriate materials.
By calling the StartFade method, this script will gradually fade the object's material from opaque to fully transparent over the duration specified by fadeDuration. After the fade completes, it switches the material to the one designated as transparentMaterial.
If you have a separate opaque and transparent material and simply want to switch between them instantly, you can replace the material like this:
csharp
meshRenderer.material = transparentMaterial;
Adjust the script according to your specific requirements, and be sure to assign the correct materials in the Inspector window for the script to work properly.
Also, note that the above example uses Unity's MeshRenderer. If your object has a SkinnedMeshRenderer (for example, if it's a character), make sure to use the correct renderer type in the script.