How to save newly bought weapon to data

Hello, I made a shop system, and this is actually my first-time using data store service.

I made a buy function here and when the weapon is successfully bought it’ll be inserted into the data.
However, whenever I buy the weapon, the weapon doesn’t count as bought and it deducts my points anyways.
I think I’m supposed to insert it to the player’s data specifically, but I don’t know how to do it here.

Remote Script:

BuyRemote.OnServerEvent:Connect(function(plr:Player,weaponname:string)
	local CurrentCost = CurrentWeapons[weaponname].Price
	--print(weaponname)
	
	local sucess = nil
	local playerdata = nil
	local attempt = 1
	
	repeat
	sucess,playerdata = pcall(function()
		return DataBase:GetAsync(plr.UserId)
	end)
	attempt += 1

	if not sucess then
		warn("Failed to load data. Attempts: "..attempt)
		end
	until sucess or attempt == 10
	if sucess then
		--print(playerdata)
		
		local function FindWeapon()
			for i, v in pairs(playerdata.OwnedWeapons) do
				if v == weaponname then
					return true
				else
					return false
				end
			end
		end
		
		local HasWeapon = FindWeapon()
		print(plr.Name.."has weapon = "..tostring(HasWeapon))
		
		if plr.leaderstats.Points.Value >= CurrentCost and HasWeapon == false then
			local Backpack = plr.Backpack
			local Tool = Weapons:FindFirstChild(weaponname):Clone()	
			if Tool then
				plr.leaderstats.Points.Value -= CurrentCost
				table.insert(playerdata.OwnedWeapons,weaponname)
			end		
		else
			print("Not Enough!/Already Have!")
		end
	end
end)
1 Like

When the weapon is bought. Save a piece of data that can be used to reference it, one way can be to save its name, so when they join again, you can grab that specific weapon, or a set of “ids”, to properly keep track of weapons.

You are basically already there, in order to save your data you simply would do:

DataBase:SetAsync(plr.UserId, playerdata.OwnedWeapons)

You do need data for the user initially however.

This is quite helpful:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.