using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.AI; public class SemanticNet : MonoBehaviour { // Definición de la red semántica private Dictionary> RedSemantica = new Dictionary>() { { "Animal", new List { "Perro", "Gato", "Pajaro" } }, { "Vehiculo", new List { "Bocho", "MonoPatin", "Bicicleta" } }, { "Moviliario", new List { "Silla", "Mesa", "Sofa" } } }; private List ObjectosDetectados = new List(); // Lista para almacenar objetos detectados private NavMeshAgent navMeshAgent; // Componente de navegación private Vector3 targetPosition; // Objetivo actual de navegación private float minDistanceToTarget = 1.0f; // Distancia mínima para considerar que el agente ha llegado al objetivo void Start() { // Obtener el componente NavMeshAgent navMeshAgent = GetComponent(); // Establecer un objetivo inicial aleatorio MoveRandomly(); } void Update() { // Verificar si el agente ha llegado al objetivo if (HasAlcanzadoObjetivo()) { // Buscar objetos en la posición actual DetectarObjectos(); // Establecer un nuevo objetivo aleatorio MoveRandomly(); } } 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 navMeshAgent.SetDestination(targetPosition); } bool HasAlcanzadoObjetivo() { // Verificar si el agente está cerca del objetivo return !navMeshAgent.pathPending && navMeshAgent.remainingDistance <= minDistanceToTarget; } void DetectarObjectos() { // Lanzar un raycast en todas las direcciones para detectar objetos RaycastHit[] hits = Physics.SphereCastAll(transform.position, 5f, transform.forward, 0f); foreach (var hit in hits) { string objectName = hit.collider.gameObject.name; // Verificar si el objeto ya fue detectado if (!ObjectosDetectados.Contains(objectName)) { ObjectosDetectados.Add(objectName); Debug.Log($"Objeto detectado: {objectName}"); // Buscar el objeto en la red semántica FindAndAddToRedSemantica(objectName); } } } void FindAndAddToRedSemantica(string objectName) { foreach (var category in RedSemantica) { if (category.Value.Contains(objectName)) { Debug.Log($"{objectName} pertenece a la categoría: {category.Key}"); return; // El objeto ya está en la red semántica } } // Si el objeto no está en la red semántica, preguntar al usuario a qué categoría pertenece Debug.Log($"Nuevo objeto detectado: {objectName}. ¿A qué categoría pertenece?"); // Se puede implementar una interfaz de usuario para que el usuario ingrese la categoría string newCategory = "Desconocido"; // Si no esta en la red lo añadimos a la categoría desconocido if (!RedSemantica.ContainsKey(newCategory)) { RedSemantica[newCategory] = new List(); } RedSemantica[newCategory].Add(objectName); Debug.Log($"{objectName} añadido a la categoría: {newCategory}"); // Guardar la red semántica actualizada en un archivo JSON SaveRedSemanticaJson(); } void SaveRedSemanticaJson() { // Convertir el diccionario a una lista de pares clave-valor List>> serializableList = new List>>(); foreach (var kvp in RedSemantica) { serializableList.Add(new KeyValuePair>(kvp.Key, kvp.Value)); } // Crear un objeto serializable para JSON SerializableSemanticNetwork serializableNetwork = new SerializableSemanticNetwork { data = serializableList }; // Convertir a JSON string json = JsonUtility.ToJson(serializableNetwork, true); // Guardar el JSON en un archivo string path = Path.Combine(Application.dataPath, "Red_semantic.json"); File.WriteAllText(path, json); Debug.Log("Red semántica guardada en: " + path); } private void OnDrawGizmosSelected() { // Dibujar el rango de detección en la escena Gizmos.color = Color.blue; Gizmos.DrawWireSphere(transform.position, minDistanceToTarget); } } // Clase auxiliar para serializar la red semántica [System.Serializable] public class SerializableSemanticNetwork { public List>> data; } // Clase auxiliar para representar un par clave-valor serializable [System.Serializable] public class KeyValuePair { public TKey key; public TValue value; public KeyValuePair(TKey key, TValue value) { this.key = key; this.value = value; } }