后端的货币进行扣除,前端如何实时显示货币数量
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-06-11 17:30:08 |
👁️ 阅读: 3
要实现后端货币扣除后前端实时显示货币数量,需要结合事件监听和UI更新。以下是完整的实现方案:
## 1. 注册货币变化事件监听
```lua
-- 定义模块级变量存储货币值
local moneyValue = "0"
-- 货币变化回调函数
local function onMoneyChange(data)
if data and data.id == 13 then -- 假设13是你要监听的货币ID
moneyValue = data.count or "0"
local idStr = data.id or "未知"
SL:print("货币13发生变化,新值:"..moneyValue..",ID:"..idStr)
-- 更新UI显示
if not GUI:Win_IsNull(moneyText) then
GUI:Text_setString(moneyText, "当前货币:"..moneyValue)
end
end
end
-- 注册事件监听
SL:RegisterLUAEvent("LUA_EVENT_MONEYCHANGE", "货币变化", onMoneyChange)
```
## 2. 创建UI显示组件
```lua
-- 创建父节点
local parent = GUI:Win_Create("MoneyDisplay", 0, 0, 0, 0, false, false, true, false, false, false, 1)
-- 创建货币显示文本
local moneyText = GUI:Text_Create(parent, "Text_money", 100, 100, 16, "#ffffff", "当前货币:0")
-- 设置字体样式
GUI:Text_setFontName(moneyText, "fonts/font5.ttf")
```
## 3. 后端扣除货币触发流程
当后端通过 `SL:SendLuaNetMsg` 发送扣除货币的请求时,服务器处理完成后会通过 `LUA_EVENT_MONEYCHANGE` 事件通知前端:
```lua
-- 示例:点击按钮扣除货币
local button = GUI:Button_Create(parent, "btn_deduct", 100, 150, "res/public/1900000612.png")
GUI:Button_setTitleText(button, "扣除货币")
GUI:addOnClickEvent(button, function()
-- 发送扣除货币请求到后端
SL:SendLuaNetMsg(1111, 1, 0, 0, "扣除货币13")
-- 前端会通过事件监听自动更新显示
SL:print("已发送扣除货币请求")
end)
```
## 4. 完整示例代码
```lua
-- 货币显示模块
local MoneyDisplay = {}
function MoneyDisplay.init()
-- 创建界面
local parent = GUI:Win_Create("MoneyMain", 0, 0, 0, 0, false, false, true, false, false, false, 1)
-- 背景
local bg = GUI:Image_Create(parent, "bg", 0, 0, "res/public_win32/1900000610.png")
GUI:setContentSize(bg, 300, 200)
-- 货币显示文本
MoneyDisplay.moneyText = GUI:Text_Create(parent, "Text_money", 150, 100, 20, "#ffff00", "货币13:0")
GUI:Text_setFontName(MoneyDisplay.moneyText, "fonts/font5.ttf")
GUI:setAnchorPoint(MoneyDisplay.moneyText, 0.5, 0.5)
-- 扣除按钮
local deductBtn = GUI:Button_Create(parent, "btn_deduct", 150, 150, "res/public_win32/1900000612.png")
GUI:Button_setTitleText(deductBtn, "扣除货币")
GUI:addOnClickEvent(deductBtn, function()
SL:SendLuaNetMsg(1111, 1, 0, 0, "扣除货币13")
SL:print("扣除请求已发送")
end)
-- 初始化货币值
MoneyDisplay.moneyValue = "0"
-- 注册事件
MoneyDisplay.registerEvents()
end
function MoneyDisplay.registerEvents()
local function onMoneyChange(data)
if data and data.id == 13 then
MoneyDisplay.moneyValue = data.count or "0"
SL:print("货币更新:"..MoneyDisplay.moneyValue)
-- 更新UI
if not GUI:Win_IsNull(MoneyDisplay.moneyText) then
GUI:Text_setString(MoneyDisplay.moneyText, "货币13:"..MoneyDisplay.moneyValue)
end
end
end
SL:RegisterLUAEvent("LUA_EVENT_MONEYCHANGE", "货币变化", onMoneyChange)
end
-- 启动模块
MoneyDisplay.init()
```
## 关键点说明:
1. **事件机制**:后端货币变化通过 `LUA_EVENT_MONEYCHANGE` 事件通知前端
2. **数据格式**:事件回调的 `data` 参数包含货币ID和数量
3. **UI更新**:在事件回调中更新文本显示组件
4. **错误处理**:使用 `GUI:Win_IsNull()` 判断组件是否有效
这样当后端扣除货币后,前端会立即收到事件通知并更新显示,实现实时同步效果。
← 返回问答库