Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Exactly how would I keep record if a player bought an item?

How Exactly would I save an item a player buys with In-Game Currency (Points, Cash, Etc.) I'm making a shop for items and I need to save an item so that players do not have to rebuy the item everytime. I know I would use datastores, but how exactly would I set it up?

1 answer

Essentially, save the name of the item when the player leaves in a PlayerRemoving event.

Check if they have the saved value when they join using a PlayerAdded event.

local obj = game.ServerStorage.PurchasableItems; --This is your item
local ds = game:GetService("DataStoreService"):GetDataStore("ItemStorage");

game.Players.PlayerAdded:Connect(function(plr) --PlayerAdded event
	local plrStorage = Instance.new("Folder");
	plrStorage.Name = "ItemStorage";
	plrStorage.Parent = plr;
	if ds:GetAsync(plr.UserId) then --Check if they own it
		obj:Clone().Parent = plrStorage; --If they do, add it to inventory
	end
end)

game.Players.PlayerRemoving:Connect(function(plr) --PlayerRemoving event
	if plr.ItemStorage:FindFirstChild(obj.Name) then --If they own it
		ds:SetAsync(plr.UserId,true); --Save it
	end
end)

Now, the code above will work for an individual object.. but you're probably going to want to expand and have multiple objects in your game. In this case, use tables and iterate through them. Save a table of what they own when they leave, iterate through it(potentially) when they join.

local objs = game.ServerStorage.PurchasableItems; --These are your items
local ds = game:GetService("DataStoreService"):GetDataStore("ItemStorage");

game.Players.PlayerAdded:Connect(function(plr) --PlayerAdded event
	local data = ds:GetAsync(plr.UserId); --Check if they own anything
	local plrStorage = Instance.new("Folder");
	plrStorage.Name = "ItemStorage";
	plrStorage.Parent = plr;
	if data then --If they do
		for _,v in next,data do --Iterate through what they own
			local obj = objs:FindFirstChild(v) --Get saved item
			if obj then --Make sure it exists
				obj:Clone().Parent = plrStorage --Clone to user's inventory
			end
		end
	else --If they don't
		print(plr.Name.." has no data to load");
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local data = {}; --Setup array for what they own
	for _,v in next,plr.ItemStorage:GetChildren() do --Iterate through inv
		data[#data+1] = v.Name; --Save name of current item
	end
	ds:SetAsync(plr.UserId,data);
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.