经济系统
经济系统提供服务器校验的货币管理、一个拍卖行(全球交易链接)和服务器端商店交易。这些服务均由 NakamaManager 自动初始化(全球交易站 Gts 和库存同步 Inventory 就位于它们旁边)。

角落里的余额并不是客户端保存的数字:它是钱包服务最后一次从服务器得知的值,而服务器也是唯一能改变它的东西。过滤条件(类别、价格、排序)会放进查询中 —— 浏览器从不下载整份目录再在本地过滤,这正是 让大型市场保持低成本的原因。

直接交易会经过顶部所标出的四个阶段:invite、offering、confirm、done。左下角的两把挂锁都必须合上,Confirm Trade 才有意义,而状态转换由服务器掌控 —— 一个不按顺序就宣称“done”的客户端会被拒绝,这正是状态机位于服务器端、而不是你眼前这个窗口里的全部原因。
架构概览
| 类 | 文件 | 职责 |
|---|---|---|
WalletService | Economy/EconomyServices.cs | 通过 Nakama 钱包进行多货币余额追踪 |
ShopService | Economy/EconomyServices.cs | 服务器校验的 NPC 商店买入/卖出 |
GTLService | Economy/EconomyServices.cs | 用于玩家间交易的全球交易链接拍卖行 |
通过 NakamaManager.Instance 访问这三者:
var wallet = NakamaManager.Instance.Wallet;
var shop = NakamaManager.Instance.Shop;
var gtl = NakamaManager.Instance.GTL;
WalletService
WalletService 管理玩家的多货币余额。Nakama 的服务器端钱包系统确保货币变更是原子的且防篡改的。
检查余额
// Refresh from server
await wallet.RefreshBalanceAsync(userId);
// Get balance for a specific currency (defaults to "gold")
long gold = wallet.GetBalance("gold");
long premiumGems = wallet.GetBalance("gems");
// Access the full currency dictionary
Dictionary<string, long> currencies = wallet.Currencies;
事件
wallet.OnBalanceChanged += (long newBalance) => { /* gold changed */ };
wallet.OnCurrencyChanged += (string currencyId, long oldValue, long newValue) =>
{
Debug.Log($"{currencyId}: {oldValue} -> {newValue}");
};
服务器权威
当 OnlineConfig.EnableServerAuthority 为 true 时,所有金钱变更都经由 OnlineCommandBridge:
// This is called internally by CommandGraph nodes (GivePlayerMoney, etc.)
bool approved = await bridge.RequestGiveMoneyAsync(amount: 500, source: "npc_reward");
服务器在应用变更前会校验来源和数额。这防止了金钱复制漏洞。
从事件脚本付款
CommandGraph 的 ChangePlayerMoney 节点(Pokémon Essentials 导入器由 Change Gold 生成的节点)会改变玩家的金钱。在线时它从不在本地直接改动金钱:
- 付款经由服务器的支出动词
mce_spend_money:一个正整数金额,每次调用最多 1,000,000,从调用者的当前角色扣除。它只能减少余额,因此既不需要开发模式也不需要游戏管理员。超过余额的付款会被整体拒绝且不写入任何内容,其他玩家的 ID 也会被拒绝; - 收入经由给予动词;
- 拒绝时金钱保持原样,节点沿 False 分支继续,因此事件可以告诉玩家钱不够。
离线时节点直接改变金钱,绝不低于 0。
ShopService
ShopService 处理带服务器端校验的 NPC 商店交易。
购买道具
bool success = await shop.BuyFromShopAsync(
shopId: "pokemart_viridian",
itemId: "potion",
quantity: 5);
服务器校验:
- 商店存在且包含该道具。
- 玩家拥有足够的货币。
- 道具可用(对于限量道具未售罄)。
出售道具
long revenue = await shop.SellToShopAsync(
itemId: "nugget",
quantity: 1);
// revenue = the amount of gold received
服务器在记入货币前校验玩家的库存中确实拥有该道具。
全球交易链接(GTL)
GTL 是一个拍卖行系统,允许玩家将怪物和道具挂单,向全球其他玩家出售。它的功能类似于热门怪物捕捉游戏中的 GTS/GTE,但带有完整的道具支持和挂单手续费。
配置
| 配置字段 | 默认值 | 说明 |
|---|---|---|
GTLListingFee | 0.05(5%) | 从挂单价格中扣除的手续费百分比 |
GTLListingDurationHours | 48 | 挂单过期前的小时数 |
MaxGTLListings | 20 | 每名玩家的最大活跃挂单数 |
挂单一只怪物
GTLListing listing = await gtl.ListMonsterAsync(
monsterId: "monster_uuid_here",
price: 50000);
// listing.Id -- unique listing ID
// listing.Fee -- the listing fee (price * GTLListingFee)
// listing.ExpiresAt -- Unix timestamp when the listing expires
// listing.Status -- GTLListingStatus.Active