Roblox模拟器游戏宠物孵化脚本异常:始终产出稀有宠物求助
问题诊断与修复
嘿,我一眼就揪出了导致你每次都孵出最高稀有度宠物的问题——你的ChoosePet函数里的权重判断逻辑完全写反了!
核心问题分析
在权重抽取的逻辑里,正确的规则是当随机生成的数值小于等于累加的权重总和时,选中当前宠物,但你现在写的是if Chance >= Counter then return d end,这直接搞反了触发条件:
- 假设你的宠物权重表是按稀有度从低到高排列(普通→稀有→史诗),权重分别为80、15、5,总权重100
- 当随机数是50时,第一次累加权重到80,50 >= 80不成立,继续循环;第二次累加至95,50 >=95还是不成立;第三次累加至100,50 >=100依旧不成立?但实际运行中,因为pairs遍历表的特性,最高稀有度宠物往往会被最后处理,而循环结束后没有兜底逻辑,就会默认返回最后一个遍历到的宠物——也就是你说的最高稀有度那只。
把判断条件改成<=,就能让权重系统回到正确的工作逻辑。
修复后的关键代码
首先修正ChoosePet函数:
local function ChoosePet(player) local Chance = math.random(1, TotalWeight) local Counter = 0 for d, c in pairs(Pets) do Counter = Counter + c[1] -- 核心修复:将 >= 改为 <= if Chance <= Counter then return d end end -- 兜底逻辑:防止权重计算错误导致无返回,返回第一个宠物 return next(Pets) end
然后简化你的GetChance函数,现在的两层循环完全是冗余的,直接通过键取值即可:
local function GetChance(ChosenPet) return Pets[ChosenPet][1] end
额外优化建议
你当前的代码在One和Triple分支里重复了大量创建宠物、更新统计的逻辑,建议把这些通用逻辑提取成单独函数,减少冗余也方便后续维护:
-- 提取创建宠物的通用函数 local function CreatePet(player, petName) local Pet = Instance.new("BoolValue") Pet.Name = petName Pet.Parent = player.Pets -- 处理宠物数量统计 local amountValue = player.PetsA:FindFirstChild(petName.." Amount") if not amountValue then amountValue = Instance.new("IntValue") amountValue.Name = petName.." Amount" amountValue.Value = 1 amountValue.Parent = player.PetsA else amountValue.Value += 1 end -- 添加等级、XP和编号属性 local Number = Instance.new("IntValue") Number.Name = "Number" Number.Value = amountValue.Value Number.Parent = Pet local Level = Instance.new("IntValue") Level.Name = "Level" Level.Value = 1 Level.Parent = Pet local Xp = Instance.new("IntValue") Xp.Name = "XP" Xp.Value = 0 Xp.Parent = Pet end
之后在One分支里只需要调用CreatePet(player, ChosenPet),Triple分支里调用三次即可,代码会清爽很多。
验证修复
修改完ChoosePet的判断条件后,你可以多测试几次孵化,不同稀有度的宠物应该会按照你设定的权重概率正常产出了。
内容的提问来源于stack exchange,提问作者PikachuPlays




