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

Roblox付费传送系统问题:FindFirstChild无反馈且代码中断

问题分析与修复方案

你的问题核心是对FindFirstChild的返回值理解错误,以及MarketplaceService事件使用方式不当,导致后续分支完全无法触发。

核心问题点

  1. FindFirstChild判断逻辑错误:
    w:FindFirstChild("CanTeleport")返回的是一个BoolValue实例(而非布尔值true/false),直接和true/false比较永远不成立,所以两个if/elseif分支都进不去。

  2. PromptPurchaseFinished使用错误:
    这是一个事件,不是可以直接用if判断的状态。必须通过Connect绑定回调函数,才能监听购买完成的结果。

  3. PromptProductPurchase参数错误:
    该方法的第一个参数必须是Player对象,而非HumanoidRootPart,原代码的调用方式本身就不合法。

修正后的代码

TeleportPart1.Touched:Connect(function(hit)
    local character = hit.Parent
    local humanoid = character:FindFirstChildOfClass("Humanoid")
    -- 优先用Humanoid判断是否为玩家角色,比直接找HumanoidRootPart更可靠
    if not humanoid then return end

    local humanoidRootPart = character:FindFirstChild("HumanoidRootPart")
    if not humanoidRootPart then return end

    print("teleport_1")
    local canTeleportValue = humanoidRootPart:FindFirstChild("CanTeleport")
    -- 先检查实例是否存在且为BoolValue类型,再判断其Value属性
    if canTeleportValue and canTeleportValue:IsA("BoolValue") then
        if canTeleportValue.Value == true then
            print("Teleport_bought")
            humanoidRootPart.CFrame = TeleportPart2.CFrame + Vector3.new(0, 5, 0)
            TeleportPart2.CanTouch = false
            task.wait(1) -- 推荐用task.wait替代wait,性能更稳定
            TeleportPart2.CanTouch = true
        else
            print("Teleport_prompt")
            local marketplaceService = game:GetService("MarketplaceService")
            local player = game.Players:GetPlayerFromCharacter(character)
            -- 传入正确的Player对象作为第一个参数
            marketplaceService:PromptProductPurchase(player, 1348388842)
            
            -- 绑定购买完成事件的回调,监听结果
            local purchaseConnection
            purchaseConnection = marketplaceService.PromptPurchaseFinished:Connect(function(purchasedPlayer, productId, wasPurchased)
                -- 验证触发购买的玩家、商品ID,以及是否购买成功
                if purchasedPlayer == player and productId == 1348388842 and wasPurchased then
                    humanoidRootPart.CFrame = TeleportPart2.CFrame + Vector3.new(0, 5, 0)
                    TeleportPart2.CanTouch = false
                    task.wait(1)
                    TeleportPart2.CanTouch = true
                    -- 完成后断开事件连接,避免内存泄漏
                    purchaseConnection:Disconnect()
                end
            end)
        end
    else
        -- 调试用:如果找不到CanTeleport实例,打印提示
        print("错误:HumanoidRootPart下不存在CanTeleport类型为BoolValue的实例")
    end
end)

额外优化说明

  • 改用Humanoid判断玩家角色:避免非角色对象(比如掉落的道具)触发传送事件。
  • 增加类型校验:确保CanTeleport是预期的BoolValue类型,避免因实例类型错误导致的逻辑异常。
  • 事件回调后断开连接:防止同一事件被重复绑定,造成不必要的内存占用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:35:26