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

Roblox Studio报错:MarketplaceService:PromptProductPurchase()需传入Player类型对象如何解决?

解决Roblox中MarketplaceService:PromptProductPurchase()的类型错误

你的代码存在两个核心问题,导致触发"player should be of type Player"错误:

  1. 事件绑定错误:script.Parent.MouseButton1Click:Connect(promptPurchase())中,你直接调用了promptPurchase()并将返回值(nil)传给Connect方法,而非传递函数本身。这会导致函数在脚本加载时立即执行,若此时LocalPlayer还未完成初始化,就会传入nil值触发类型错误。
  2. LocalPlayer的使用场景错误:如果这段代码运行在服务器脚本中,Players.LocalPlayer无法获取有效玩家实例——LocalPlayer仅在客户端脚本(如StarterGui、StarterPlayerScripts下的脚本)中可用,服务器需通过Players.PlayerAdded事件获取玩家。

修复方案

情况1:脚本为客户端脚本(放置在StarterGui/StarterPlayerScripts等客户端容器)

修改后的代码:

local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer

local productid = 1340456024

local function promptPurchase()
    -- 先校验LocalPlayer是否存在,避免加载阶段的nil问题
    if LocalPlayer then
        MarketplaceService:PromptProductPurchase(LocalPlayer, productid)
    end
end

-- 注意此处不要加括号,直接传递函数引用
script.Parent.MouseButton1Click:Connect(promptPurchase)

情况2:脚本为服务器脚本

服务器无法直接触发玩家的购买界面,PromptProductPurchase是客户端专属API。推荐将脚本移至客户端容器中,或通过RemoteEvent让客户端发起购买请求(但购买提示仍需在客户端调用)。

关键注意点

  • PromptProductPurchase必须在客户端执行,因为它需要弹出玩家的购买弹窗,服务器无法操作客户端界面。
  • 绑定事件时,务必传递函数引用(仅写函数名,不加括号),加括号会立即执行函数并传递返回值,这是Roblox脚本开发中的常见误区。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 07:10:33