如何开发一个简单的游戏对话框模块?
前言
对话框可以增强玩家游戏沉浸感,增加与NPC情感联系,甚至画外音补充角色内心独白。总而言之,是一个非常重要,常见的功能,所以我分享一下对话框系统简单的框架流程,有兴趣的朋友可以基于此再进行二次开发。
对话演示
代码展示
代码结构:
场景结构:
DialogueData.cs
using System.Collections.Generic;
namespace XiaYun.Dialogue
{
public static class DialogueData
{
public class Data
{
public int sid;
public string name;
public string content;
public int[] jumpList;
}
public static Dictionary<int, Data> Datas = new Dictionary<int, Data>()
{
[1] = new Data()
{
sid = 1,
name = "玩家",
content = "你好呀,NPC",
jumpList = new []{2}
},
[2] = new Data()
{
sid = 2,
name = "NPC",
content = "你好玩家,可以帮个忙吗?",
jumpList = new []{3, 4}
},
[3] = new Data()
{
sid = 3,
name = "玩家",
content = "当然,乐意效劳"
},
[4] = new Data()
{
sid = 4,
name = "玩家",
content = "抱歉,我还有要事在身"
}
};
}
}
DialogueSelectBox.cs
using UnityEngine;
using UnityEngine.UI;
namespace XiaYun.Dialogue
{
public class DialogueSelectBox : MonoBehaviour
{
public Button button;
public Text text;
}
}
DialogueUI.cs
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace XiaYun.Dialogue
{
public class DialogueUI : MonoBehaviour
{
public Button btn开始对话;
public GameObject go对话节点;
public Text text名字;
public Text text内容;
public Button btn前进;
public List<DialogueSelectBox> boxList;
private int curSid;
private Action<int> action;
private void Start()
{
btn开始对话.onClick.AddListener(() =>
{
btn开始对话.gameObject.SetActive(false);
go对话节点.SetActive(true);
StartDialogue(1, (sid) =>
{
switch (sid)
{
case 3:
// 寻路至任务点等等...
Debug.Log("对话结束,自动行进下一步");
break;
}
});
});
btn前进.onClick.AddListener(() =>
{
var data = DialogueData.Datas[curSid];
if (data.jumpList == null || data.jumpList.Length != 1)
{
return;
}
DoJump(data.jumpList[0]);
});
}
public void StartDialogue(int sid, Action<int> action)
{
this.action = action;
DoJump(sid);
}
private void DoJump(int sid)
{
curSid = sid;
var data = DialogueData.Datas[sid];
if (data.jumpList == null || data.jumpList.Length == 0)
{
CloseDialogue();
return;
}
text名字.text = data.name;
text内容.text = data.content;
// 仅做演示,正常不能写
if (data.jumpList != null && data.jumpList.Length > 1)
{
for (int i = 0; i < boxList.Count; i++)
{
var box = boxList[i];
box.gameObject.SetActive(i < data.jumpList.Length);
int nextSid = data.jumpList[i];
box.text.text = DialogueData.Datas[nextSid].content;
box.button.onClick.RemoveAllListeners();
box.button.onClick.AddListener(() =>
{
DoJump(nextSid);
});
}
btn前进.gameObject.SetActive(false);
}
else
{
for (int i = 0; i < boxList.Count; i++)
{
boxList[i].gameObject.SetActive(false);
}
btn前进.gameObject.SetActive(true);
}
}
private void CloseDialogue()
{
btn开始对话.gameObject.SetActive(true);
go对话节点.SetActive(false);
action?.Invoke(curSid);
}
}
}
本文作者:陈侠云
本文链接:https://www.cnblogs.com/chenxiayun/p/18735919
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步