using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using System.IO; public class MainAgent : MonoBehaviour { private NavMeshAgent agent; private List agentDataList = new List(); private Vector3 targetPosition; // Objetivo actual de navegación void Start() { agent = GetComponent(); StartCoroutine(BuscaPorAgentes()); } void Update() { if (!agent.pathPending && agent.remainingDistance < 0.5f) { //Vector3 randomPos = new Vector3(Random.Range(-10, 10), 0, Random.Range(-10, 10)); //agent.SetDestination(randomPos); MoveRandomly(); } } IEnumerator BuscaPorAgentes() { while (true) { GameObject[] agents = GameObject.FindGameObjectsWithTag("Agent"); Debug.Log("Número de agentes encontrados: " + agents.Length); foreach (GameObject ag in agents) { if (ag != this.gameObject) { AgentInfo info = ag.GetComponent(); if (info != null) { AgentData data = new AgentData(info.id, ag.transform.position, info.type); agentDataList.Add(data); Debug.Log("Datos recopilados de: " + info.id); } } } SaveDataToJson(); yield return new WaitForSeconds(10); } } void SaveDataToJson() { if (agentDataList.Count == 0) return; string path = Path.Combine(Application.dataPath, "agentsData.json"); //string path = Application.persistentDataPath + "/agentsData.json"; AgentList dataWrapper = new AgentList(agentDataList); string json = JsonUtility.ToJson(dataWrapper, true); File.WriteAllText(path, json); Debug.Log("Datos guardados en: " + path); } void MoveRandomly() { // Generar una posición aleatoria dentro del NavMesh Vector3 randomDirection = Random.insideUnitSphere * 10f; randomDirection += transform.position; NavMeshHit hit; NavMesh.SamplePosition(randomDirection, out hit, 10f, NavMesh.AllAreas); targetPosition = hit.position; // Asignar la posición al NavMeshAgent agent.SetDestination(targetPosition); } private void OnDrawGizmos() { Gizmos.color = Color.blue; //Gizmos.DrawWireSphere(transform.position, targetPosition); } } [System.Serializable] public class AgentList { public List agents; public AgentList(List agents) { this.agents = agents; } }