so as the question says i would like the game to save the players health and give it to them on return which obviously means its datastore time (yes i will convert to datastore2 later) but with this script i made it says humanoid is not a nil value (line 21)and before i added workspace.name to line 20 it wouldnt say anything at all
script:
local Data = game:GetService("DataStoreService"):GetDataStore("Health") game.Players.PlayerAdded:Connect(function(plr) local Folder = Instance.new("Folder") Folder.Name = "Health" Folder.Parent = plr local Health = Instance.new("IntValue") Health.Name = "Health" Health.Parent = Folder print("Gave "..plr.Name.." Health Data") local SavedItems = Data:GetAsync(plr.UserId) if SavedItems then Health.Value = SavedItems.Health print(plr.Name.." had Health Data") else Health.Value = 100 print(plr.Name.." didn't have Health Data") end local name = plr.Name local Character = workspace.name or plr.Character or plr.CharacterAdded:Wait() Character.Humanoid.Health = Health.Value Health.Changed:Connect(function() Character.Humanoid.Health = Health.Value Character.Humanoid.Changed:Connect(function() Health = plr.Character.Humanoid.Health end) end) end) game.Players.PlayerRemoving:Connect(function(plr) local Saving = {["Health"] = (plr.Health).Health.Value; } Data:SetAsync(plr.UserId, Saving) print("Saved "..plr.Name.."'s Health Data") end)
The problem is in fact on line 20:
local Character = workspace.name or plr.Character or plr.CharacterAdded:Wait()
You're saying workspace.name
. I am not sure if name
is deprecated, but it still references the Name
property. You'll want to index using square brackets, like so:
workspace[name]
x or y
evaluates to x
if x
is truthy, y
otherwise.
Truthy values are anything that is not false
or nil
. Since the Name
property is a string, it is not false or nil. When you did workspace.name or plr.Character or plr.CharacterAdded:Wait()
, workspace.name was returned as it didn't have to bother checking everything else, since the result was going to be truthy.
However I don't suggest you index the character in the workspace, as it can cause conflict if any items in there have the same name as the player. Your scripts would break if Terrain or Part joined your game! Use the Character
property instead.
So simply do local Character = plr.Character or plr.CharacterAdded:Wait()
.