You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Roblox三倍金币GamePass脚本异常:hasPass返回nil求助

问题分析与修复方案

你的脚本存在几个关键问题,导致hasPass返回nil或者无法正确对应玩家的GamePass状态:

核心问题

  • 全局变量hasPass无法关联单个玩家:当多个玩家加入游戏时,全局的hasPass会被最后执行checkForPass的玩家覆盖,触发Touched事件时,无法确定这个变量对应的是当前触发的玩家。
  • 未处理pcall失败的情况:如果UserOwnsGamePassAsync调用失败(比如网络问题),hasPass会保持初始的false,但你没有任何错误提示或重试逻辑。
  • Touched事件未针对当前玩家验证状态:就算玩家在游戏过程中购买了GamePass,脚本也不会重新检查,而是一直使用全局的旧值。

修复后的脚本

local debounce = false
local passID = 148667250
local MarketplaceService = game:GetService("MarketplaceService")

-- 检查玩家是否拥有GamePass,并将状态存在玩家的Attribute中
local function checkForPass(player)
    local success, hasPass = pcall(function()
        return MarketplaceService:UserOwnsGamePassAsync(player.UserId, passID)
    end)
    
    if success then
        player:SetAttribute("HasTripleCoinPass", hasPass)
    else
        warn("检查GamePass失败:" .. message)
        -- 失败时默认设为false,也可以添加重试逻辑
        player:SetAttribute("HasTripleCoinPass", false)
    end
end

-- 玩家加入时检查GamePass
game.Players.PlayerAdded:Connect(checkForPass)

-- 监听玩家购买GamePass的事件,实时更新状态
MarketplaceService.PromptGamePassPurchaseFinished:Connect(function(player, passId, wasPurchased)
    if passId == passID and wasPurchased then
        player:SetAttribute("HasTripleCoinPass", true)
    end
end)

script.Parent.Touched:Connect(function(hit)
    if debounce then return end
    debounce = true

    local humanoid = hit.Parent:FindFirstChildOfClass("Humanoid")
    if not humanoid then 
        debounce = false
        return 
    end

    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
    if not player then 
        debounce = false
        return 
    end

    -- 获取当前玩家的GamePass状态
    local hasPass = player:GetAttribute("HasTripleCoinPass") or false
    print(hasPass)

    -- 播放音效
    local sound = script.Parent.CoinSFX:Clone()
    sound.Parent = player
    sound:Play()

    -- 增加金币
    if hasPass then
        player.leaderstats.Coins.Value += 3
    else
        player.leaderstats.Coins.Value += 1
    end

    -- 清理资源
    script.Parent:Destroy()
    task.wait(0.5)
    sound:Destroy()

    debounce = false
end)

关键修改点

  • 用玩家的Attribute存储每个玩家的GamePass状态,避免全局变量的冲突问题。
  • 处理pcall的返回值,直接获取UserOwnsGamePassAsync的结果,同时添加错误提示。
  • 监听PromptGamePassPurchaseFinished事件,玩家在游戏内购买GamePass后实时更新状态。
  • Touched事件中针对当前触发的玩家获取状态,确保每个玩家的判断正确。
  • 优化了代码逻辑,比如提前返回减少嵌套,用FindFirstChildOfClass更准确查找Humanoid。

内容的提问来源于stack exchange,提问作者sjaf553

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 06:43:12