I’m working on a system that detects codes and rewards you but I’m having trouble with saving codes that have already been used.
Heres my code:
local function onButtonPress()
textbox.FocusLost:Connect(function(Enter)
game.ReplicatedStorage.GameRemotes.RedeemCode.OnClientEvent:Connect(function(redeemedcodes)
print(redeemedcodes[2])
end)
for i, v in pairs(Codes) do
if Enter then
if textbox.Text == Codes[i][1] and Codes[i][2] == false then
Codes[i][2] = true
game.ReplicatedStorage.GameRemotes.RedeemCode:FireServer(Codes[i])
textbox.Text = "Code Redeemed!"
wait(1)
textbox.Text = ""
else
if Codes[i][2] == true and textbox.Text == Codes[i][1] then
textbox.Text = "Code Already Redeemed!"
wait(1)
textbox.Text = ""
else
if textbox.Text ~= Codes[i][1] then
textbox.Text = "Invalid Code!"
wait(1)
textbox.Text = ""
end
end
end
end
end
end)
end
script.Parent.Parent.Left.Content.Codes.MouseButton1Click:Connect(onButtonPress)
script.Parent.Parent.Left.Content.Codes.TouchTap:Connect(onButtonPress)
I’m not quite sure I understand what’s going on in your code, but here’s what I would do:
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local codesDatastore = game:GetService('DataStoreService'):GetDataStore("codesDatastore")
ReplicatedStorage.GameRemotes.RedeemCode.OnServerEvent:Connect(function(player: Player, reedemedCode: string)
--Assing the redeemed code is a string, we then get the table of codes the player has already used.
local codes = codesDatastore:GetAsync("Player" .. player.UserId) or {}
table.insert(codes, reedemedCode)
codesDatastore:SetAsync("Player".. player.UserId, reedemedCode)
ReplicatedStorage.GameRemotes.RedeemCode:FireClient(player, reedemedCode)
print(reedemedCode)
end)
game.Players.PlayerRemoving:Connect(function(player: Player)
local Codes = codesDatastore:GetAsync("Player" .. player.UserId)
print(Codes)
end)
This should make sense, but I don’t think you are sending RedeemedCode as a string, you’re sending it as an array.
I think you’re making a few mistakes. When using a DataStore, you should be using it under one central name, not using a unique DataStore for every player. (While this isn’t theoretically incorrect, it’s not what most developers I know do).
Second of all, you’re only setting the most recent code of the player used, and not adding it to an array.
Third, the client has no way of knowing if its used the code, so you need to communicate that information with the client, which will require another event call.