como hago un sistema de dialogos/mensajes para mi ...

Создано: 25 июня 2025 г.

Отвечено с использованием O3 от Chat01

Вопрос

como hago un sistema de dialogos/mensajes para mi juego de pseudo-chat en unity? lo quiero hacer con excel (nada de jsons y esas madres). La idea es que los personajes se comuniquen a traves de "mensajes" de texto y el jugador tenga opciones para responder y ramificar la historia.

Мысль

Guiding dialogue system setup

I’m thinking through how to help with a chat-based dialogue system for Unity using Excel. The user wants to avoid JSON files, so I’ll be suggesting how to structure the dialogue in Excel, maybe with rows for messages, choices, and branching paths.

I should also explain how to then import the Excel data into Unity, suggesting some C# scripting to manage the flow and decision-making for the player. Sample code could be useful here to help the user get started! I'll make sure to stay focused on their exact needs.

Guiding the Excel dialogue system

The user wants help creating a dialogue system in Unity using Excel, which means we can guide them through importing Excel data without JSON files. I’ll suggest both Excel-reading libraries like ExcelDataReader and EPPlus, plus a CSV method if they want ease of use. We can show how to structure the Excel file with columns for messages and options, and then suggest a C# class and DialogueManager for managing in-game conversations. Since they wrote in Spanish, I’ll answer in a casual and friendly tone, matching their style!

Thought for 16 seconds

Ответ

Aquí tienes una manera práctica (y sin JSON 😉) de montar un sistema de “pseudo-chat” ramificado en Unity usando un archivo Excel como única fuente de datos.


1. Estructura del Excel

Crea un libro con una sola hoja llamada, por ejemplo, Dialogos (o varias si te gusta tener todo ordenado). Usa una fila por mensaje:

IDRemitenteTextoOpción 1 TextoOpción 1 SiguienteIDOpción 2 TextoOpción 2 SiguienteIDCondiciónEfecto
0Ana“¡Hola! ¿Cómo estás?”“Bien”1“Mal”2
1Jugador“Genial.”“¿Qué planes?”3score+1
2Jugador“Pues regular…”“Ánimo”3score-1
3Ana“Vamos al cine.”“Sí”4“Otro día”5score>=0
  • ID: clave única para cada nodo.
  • Remitente: quién envía el mensaje (útil para retratos o color de burbuja).
  • Texto: lo que se muestra en pantalla.
  • Opción N Texto / SiguienteID: lo que puede elegir el jugador y a qué ID salta.
  • Condición / Efecto (opcional): expresiones simples para variables (“score>=0”) o para modificarlas (“score+1”).

Guarda el libro como .xlsx en la carpeta StreamingAssets/ (Unity la copia tal cual dentro del build, así que no hace falta rehacer la hoja en cada iteración).


2. Leer Excel en Unity

Biblioteca ligera

  1. ExcelDataReader
    • MIT, funciona bien en Unity → Packages/manifest.json:
    jsonc
    "com.system.exceldatareader": "https://github.com/ExcelDataReader/ExcelDataReader.Unity.git"
  2. Activa System.Text.Encoding.CodePages en Player Settings → Other Settings → Api Compatibility Level >= .NET 4.x y añade:
    csharp
    System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

Cargar el libro

csharp
using ExcelDataReader; using System.Data; using UnityEngine; using System.IO; using System.Linq; public class DialogueLoader { public static Dictionary<int, DialogueNode> LoadSheet(string fileName) { string path = Path.Combine(Application.streamingAssetsPath, fileName); using var stream = File.Open(path, FileMode.Open, FileAccess.Read); using var reader = ExcelReaderFactory.CreateReader(stream); var result = reader.AsDataSet().Tables[0]; // primera hoja return Enumerable.Range(1, result.Rows.Count - 1) // salta cabecera .Select(r => ParseRow(result.Rows[r])) .ToDictionary(n => n.ID, n => n); } static DialogueNode ParseRow(DataRow row) { int GetInt(string col) => int.TryParse(row[col]?.ToString(), out var v) ? v : -1; string GetStr(string col) => row[col]?.ToString() ?? ""; return new DialogueNode { ID = GetInt("ID"), speaker = GetStr("Remitente"), text = GetStr("Texto"), options = new[] { new DialogueOption{ text = GetStr("Opción 1 Texto"), nextID = GetInt("Opción 1 SiguienteID")}, new DialogueOption{ text = GetStr("Opción 2 Texto"), nextID = GetInt("Opción 2 SiguienteID")} }.Where(o => !string.IsNullOrWhiteSpace(o.text)).ToList(), condition = GetStr("Condición"), effect = GetStr("Efecto") }; } } public class DialogueNode { public int ID; public string speaker; public string text; public List<DialogueOption> options; public string condition; public string effect; } public class DialogueOption { public string text; public int nextID; }

3. Gestor de diálogo

csharp
public class DialogueManager : MonoBehaviour { public ChatUI ui; // tu script de interfaz (TextMeshPro, botones, etc.) Dictionary<int, DialogueNode> nodes; int currentID; Dictionary<string,int> vars = new(); // score, karma, etc. void Start() { nodes = DialogueLoader.LoadSheet("Dialogos.xlsx"); StartConversation(0); } void StartConversation(int id) => ShowNode(id); void ShowNode(int id) { if (!nodes.TryGetValue(id, out var node)) return; if (!IsAllowed(node.condition)) { ShowNode(id+1); return; } // fallback ui.AddBubble(node.speaker, node.text); ui.ClearChoices(); foreach (var opt in node.options) ui.AddChoice(opt.text, () => OnChoose(opt)); ApplyEffect(node.effect); currentID = id; } void OnChoose(DialogueOption opt) => ShowNode(opt.nextID); bool IsAllowed(string cond) { if (string.IsNullOrEmpty(cond)) return true; // mini parser super simple: “score>=0” var parts = System.Text.RegularExpressions.Regex.Match(cond, @"(\w+)\s*([><=]+)\s*(-?\d+)"); if (!parts.Success) return true; int value = vars.GetValueOrDefault(parts.Groups[1].Value, 0); int rhs = int.Parse(parts.Groups[3].Value); return parts.Groups[2].Value switch { ">" => value > rhs, ">=" => value >= rhs, "<" => value < rhs, "<=" => value <= rhs, "=" => value == rhs, _ => true }; } void ApplyEffect(string eff) { if (string.IsNullOrEmpty(eff)) return; // ejemplo “score+1” var m = System.Text.RegularExpressions.Regex.Match(eff, @"(\w+)([+\-]\d+)"); if (!m.Success) return; string key = m.Groups[1].Value; int delta = int.Parse(m.Groups[2].Value); vars[key] = vars.GetValueOrDefault(key,0) + delta; } }

El UI Chat puede ser tan simple como:

  • ScrollView con VerticalLayoutGroup para las “burbujas” (TextMeshProUGUI).
  • Prefab para las burbujas recibidas y enviadas (cambia color/fondo según speaker).
  • Contenedor de botones de opciones bajo el chat.

4. Tips para que la herramienta sea cómoda

TrucoVentaja
Nombra las columnas con espacios y acentos si quieres; el loader las busca por cabeceraMás legible para guionistas; no necesitan saber de código
Comentarios: añade una columna “Notas” que ignores al leerFeedback de QA sin romper nada
Variables globales: suma columnas de booleanos (flag_habla_ana) si prefieres checks directosMenos regex
Pruebas rápidas: guarda el .xlsx como CSV en un macro y recarga en hot-reloadNada de volver a compilar
Google Sheets → Excel: deja que el guionista trabaje online; bajas el .xlsx cuando quierasFlujo colaborativo

5. Qué evita problemas

  1. Licencias: ExcelDataReader (MIT) es segura para publishing. EPPlus cambió a Polyform (ojo).
  2. Plataformas móviles: pon los .xlsx en StreamingAssets/ para que lleguen intactos a Android/iOS.
  3. Performance: carga el libro una sola vez y cachea; son milisegundos.
  4. Debug: si no encuentras un ID, muestra una burbuja “<missing 17>” para pillar huecos al vuelo.

¡Y listo! Con esto tienes un “motorcito” de chat ramificado 100 % Excel-friendly, fácil de ampliar y sin tocar JSON ni editores externos. Cuando quieras meter más profundidad (timers, mensajes asincrónicos, multimedia) solo extiende la hoja con nuevas columnas y amplía el DialogueManager. ¡Éxitos con tu juego!

Поделиться этим Q&A