LocalScript Issue

Hey guys. I’m having an issue with my LocalScript. I noticed LocalScripts usually work well when it comes to loops, but when it comes to functions, the LocalScript cannot comprehend what is happening or just seems a bit stubborn. What do I do? My goal is to detect when the player’s character has been added and so the HP text will change. It worked fine with the loop, but it was constantly running in the background which I don’t need. However, using the functions though, the script absolutely refuses to run at all. What do I do???

Code:

local Players = game.Players or game:GetService("Players")
local Client = Players.LocalPlayer
local HPBar = script.Parent
local RemainingHP = HPBar["Remaining Health"]
local RunService = game:GetService("RunService")
local CharacterFound = false
local PlayerGui = Client:WaitForChild("PlayerGui", math.huge)
local Descendants = game.Workspace:GetDescendants()
local Hit = script.Hit

local function SetHP(Humanoid)
	local CurrentHP = Humanoid.Health
	local Signal = Humanoid:GetPropertyChangedSignal("Health")
	Signal:Connect(function()
		if Humanoid.Health < CurrentHP or Humanoid.Health > CurrentHP then
			CurrentHP = Humanoid.Health
			RemainingHP.Text = tostring(CurrentHP.."/"..Humanoid.MaxHealth)
			Hit:Play()
		end
	end)
end

Client.CharacterAdded:Connect(function(Character)
	if Character ~= nil then
		local Humanoid = Character:WaitForChild("Humanoid", math.huge)
		if Humanoid ~= nil then
			SetHP(Humanoid)
		end
	end
end)

game.Workspace.ChildAdded:Connect(function(Child)
	if Child.Name == Client.Name then
		local Character = Child
		local Humanoid = Character:WaitForChild("Humanoid", math.huge)
		if Character ~= nil and Humanoid ~= nil then
			SetHP(Humanoid)
		end
	end
end)

The script is parented inside of a Frame in a Gui. It’s also a ServerScript, but the RunContext has been changed to Client.

in a server script you can’t use client sided script stuff… “game.players.localplayer” …

1 Like

Yes, what @Kyl3ST said was correct. You’d have to wrap all your code in the PlayerAdded event.

Didn’t see the bottom part. Never mind what I said.

However, I would recommend transferring the code to a LocalScript instead of having a Script with Client as its RunContext.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.