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

How would i go about storing Humanoid properties?

I am trying to store the Humanoid properties so when a character resets or leaves the game, the maxhealth and health save, but doesnt work, here is the script-

local datastore = game:GetService("DataStoreService"):GetDataStore("NPS")

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		local humanoid = character.Humanoid
		
		local key = "user-" .. player.userId

		local storeditems = datastore:GetAsync(key)
		
		if storeditems then
			humanoid.MaxHealth = storeditems[1]
			humanoid.Health = storeditems[2]	
		else
			local items = {humanoid.MaxHealth, humanoid.Health}
			datastore:SetAsync(key, items)
		end
	end)
	player.CharacterRemoving:Connect(function(character)
		local items = {character.Humanoid.MaxHealth, character.Humanoid.Health}
		local key = "user-" .. player.userId
		
		datastore:SetAsync(key, items)
	end)
end)

1 comment

0

Try Players.PlayerRemoving instead of CharacterRemoving. If not, try to use game:BindToClose() along side it.

1 answer

✓ Accepted answer

Your code works for me (make sure API Services are enabled in your game settings). Literally, all I did was change userId to UserId. Even then, I feel like the code should have still worked, because I believe userId is deprecated, but still functional.

local datastore = game:GetService("DataStoreService"):GetDataStore("NPS")

game.Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(character)
        local humanoid = character.Humanoid

        local key = "user-" .. player.UserId

        local storeditems = datastore:GetAsync(key)

        if storeditems then
            humanoid.MaxHealth = storeditems[1]
            humanoid.Health = storeditems[2]    
        else
            local items = {humanoid.MaxHealth, humanoid.Health}
            datastore:SetAsync(key, items)
        end
    end)
    player.CharacterRemoving:Connect(function(character)
        local items = {character.Humanoid.MaxHealth, character.Humanoid.Health}
        local key = "user-" .. player.UserId

        datastore:SetAsync(key, items)
    end)
end)

Also, like Davydas said, you'll want to consider using an event other than CharacterAdded and CharacterRemoving. When I tested this, I immediately received a warning, regarding the overflow of requests we were sending to the datastore. Imagine how bad this could be if you had a full server of this! Try thinking of when you really need to store this information, such as before the player leaves the game.

2 comments

0

Ok, i get it, i used humanoid.died function...Thank You~

0

Humanoid.Died could be an even worse option, just saying

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