so im trying to make a shop and i need an item to permanently set a value to unlock a power, how exactly would i do this? here's the item's code so far:
01 | Tool = script.Parent |
02 | local replicatedstorage = game:GetService( "ReplicatedStorage" ) |
03 | local useevent = replicatedstorage.BuyDistraction |
04 | local cd = false |
05 |
06 | Tool.Activated:Connect( function () |
07 | if cd = = true then return end |
08 | cd = true |
09 | local plr = game.Players.LocalPlayer |
10 | local char = plr.Character |
11 | local hum = char.Humanoid |
12 | useevent:FireServer() |
13 | end ) |
and here's the useevent
1 | game.ReplicatedStorage.BuyDistraction.OnServerEvent:Connect( function (player) |
2 |
3 | end ) |
it is empty right now, as i do not know what to put in it. any help would be appreciated!
You may achieve data persistence via the use of DataStore
s.
These are essentially a direct way to save data onto Roblox's servers, but you should be mindful of their limits. An implementation of them into your code would look like this:
01 | local ReplicatedStorage = game:GetService( "ReplicatedStorage" ) |
02 | local DataStoreService = game:GetService( "DataStoreService" ) -- https://developer.roblox.com/en-us/api-reference/class/DataStoreService |
03 |
04 | local dataStore = DataStoreService:GetDataStore( "DataStore_Name" ) -- Retrieves a DataStore with the given name. |
05 |
06 | ReplicatedStorage.BuyDistraction.OnServerEvent:Connect( function (Player) |
07 | pcall ( function () -- DataStores may often fail to save information if something goes wrong; pcall allows your script to keep executing if what's wrapped inside of pcall's function() throws an error. This is especially used in error handling: it returns two values, one being a boolean indicating the function's success, and the other being the error message that would've otherwise been printed to the output window. |
08 | dataStore:SetAsync(Player.UserId, true ) -- Sets the value of the DataStore key that is equal to the player's User ID to true (assuming all you need is to check whether they own the power via a boolean). |
09 | end ) |
10 | end ) |
This essentially saves the boolean true
to the key [UserId]
within the DataStore upon receiving OnServerEvent
from the remote. To handle DataStore errors and actually retrieve data on join is another story. On a side note: sanity checks. You definitely need to add some way for the server to check the validity of what's being sent by the Client via BuyDistraction
, or else anyone with a low level injector could exploit it.