I have been trying to create a brick that when it is clicked it prompts a purchase to buy popcorn however when I try to click it, it says MarketplaceService:PromptProductPurchase() player should be of type of Player, but is of type nil? The clicking part works as i did some tests and in the output it prints hi. This is in a clickable brick not a gui.
function sup() print("hi") local id = 562717431 local plr = game.Players.LocalPlayer local MP = game:GetService("MarketplaceService") MP:PromptProductPurchase(plr,id) end script.Parent.ClickDetector.MouseClick:Connect(sup)
Players.LocalPlayer is nil to the server.
The top ancestor (excluding the
DataModel and the
Players service) of a
LocalScript is typically the
LocalPlayer. You can place them in
ReplicatedFirst and have them execute there but we aren't going to talk about that. And
LocalScripts run for one client, you.
Scripts run on the server, a poweful computer that is located in the Roblox HQ.
Think of it as your school classmates and your teacher. Think of your school classmates as other clients, and think of your teacher as the server. If you told your teacher to "get the local student," your teacher would be very confused, because which student is the local student? For this reason,
Players.LocalPlayer is nil on the server. Your game could have multiple players in it, and when you try using
Players.LocalPlayer, it can't just randomly pick a player. It makes no sense.
Code cannot read your mind. This is why it must be all typed out. So instead of doing this:
make a part inside of the workspace with color red
You must do this:
-- or something like this local part = Instance.new("Part"); part.BrickColor = BrickColor.new("Really red"); part.Parent = game:GetService("Workspace");
When you listen for the
ClickDetector.MouseClick event, the listener gets the player who clicked as an argument. So use that.
id are constants, so why declare them each time the button is clicked? One declaration will suffice.
local MarketplaceService = game:GetService("MarketplaceService"); local PRODUCT_ID = 562717431; script.Parent.ClickDetector.MouseClick:Connect(function(client) print("hi"); MarketplaceService:PromptProductPurchase(client, PRODUCT_ID); end);