“MarketplaceService:PromptGamePassPurchase() player should be of type Player, but is of type nil”
My output floods with this error when the player touches the script parent, It says that something is wrong with line 5 of the script but i am not sure what is wrong with it.
The script works fine just like i wanted to but this error flooding my output is annoying.
Here is the script.
function onTouch(hit)
local player = game.Players:FindFirstChild(hit.Parent.Name)
game:GetService("MarketplaceService"):PromptGamePassPurchase(player, 0)
end
script.Parent.Touched:connect(onTouch)
Edit; Not all parts have this error only some, weird.
You should check to make sure that the player variable isn’t nil. It is possible for soemthing other than a character’s direct child to touch the prompt button part.
function onTouch(hit)
local player = game.Players:FindFirstChild(hit.Parent.Name)
if player ~= nil then
game:GetService("MarketplaceService"):PromptGamePassPurchase(player, 0)
end
end
In the future, I would recommend that you do some research by inspecting free models that accomplish what you want or looking through the Developer Hub. The function Players.GetPlayerFromCharacter would help you in this circumstance. There’s even a code sample right on the page that confirms the player’s existence first before acting.
GetPlayerFromCharacter is the canonical way to fetch a player object from a character model over finding a child in the Players service named the same as a model. Once you run this call, you can check if the player exists and then prompt them if they do.
@VitalWinter’s code will do the trick, but I’ll provide one for GetPlayerFromCharacter.
A note @ Vital: you don’t need the not equals operator unless you’re checking for an explicit value. In this case, nil or false are both unpassable conditions.
local Players = game:GetService("Players")
local MarketplaceService = game:GetService("MarketplaceService")
local function onTouch(hit)
local player = Players:GetPlayerFromCharacter(hit.Parent)
if player then -- Guaranteed to return a Player object or nil
MarketplaceService:PromptGamePassPurchase(player, 0)
end
end
script.Parent.Touched:Connect(onTouch)