The code shown below is to set the players stats to the correct values once they spawn into the game, and I think it just looks kinda bad rn.
I am fairly sure that there is a better way to handle this data that would look nicer and maybe even function better.
I’m just having a hard time figuring out what I could change and would appreciate any feedback
the code is in a server script separate from the character.
local data = DataStore:GetAsync(tostring(player.UserId))
if data == nil then
data = {
StoredColour = haircolour,
Ability = 3,
...
}
DataStore:SetAsync(tostring(player.UserId), data)
end
for key, value in data do
humanoid:SetAttribute(key, val)
end
This logic needs to exist somewhere so if you’re just wanting to make it look a bit neater as @kingerman88 mentioned a loop could help with that. Also, unless there are actual problems I wouldn’t get so fixated on fixing/improving code simply because it looks bad.
Just a little critique from @kingerman88 's reply:
If you wrap this all in a pcall and it errors, then none of this data will be set. Instead you should only specifically pcall for interacting with the datastore, and if errors it’ll fallback to the default data instead.
Here’s the slightly adjusted version with some other general cleanup:
local key = tostring(player.UserId)
local success, data = pcall(DataStore.GetAsync, DataStore, key)
if not (success and data) then
data = {
StoredColour = haircolour,
Ability = 3,
...
}
pcall(DataStore.SetAsync, DataStore, key, data)
end
for key, value in data do
humanoid:SetAttribute(key, value)
end
Just as a side note, if you plan on actively changing these values (im assuming you likely will be), things may tend to fall apart with potential rate limits or general code smell related to datastore. I suggest looking into open source datastore libraries such as ProfileStore: ProfileStore - Save your player data easy (DataStore Module). It may take some learning and research but will benefit you and your code in the long term. Not to mention ProfileStore specifically pairs well with Replica (by the same creator) for replicating the data to the client which seems to be the point of attributes in this code snippet anyways.
Sorry for not responding sooner, but thank you all so much for taking the time to respond. I will be sure to look into the resources you have provided. Thanks again for the help!
i was gonna post this but it was solved alreadly but i have not tested this but i think this would work!
pcall(function()
local userId = tostring(player.UserId)
local data = DataStore:GetAsync(userId) or {
StoredColour = haircolour,
Agility = 3,
Strength = 3,
SwingSpeed = 3,
FallResistance = 0,
Weight = 0,
Stamina = 20,
MaxStamina = 20
}
if not DataStore:GetAsync(userId) then
DataStore:SetAsync(userId, data)
print("new", haircolour)
else
haircolour = data.StoredColour
print("stored", haircolour)
end
for key, value in pairs(data) do
humanoid:SetAttribute(key, value)
end
end)