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

Heal tool won't work, player.Character is nil, breaks the script, how do i fix that?

So the main error I've had is the server sees 'c' (my variable for player.Character) as nil. The server then doesn't know what 'local h = c.Humanoid' is and then my entire script doesn't work. I'm not sure how to fix this and I need some help figuring it out.

Local Script:

local player = game.Players.LocalPlayer
local c = player.Character
local h = c.Humanoid
local tool = script.Parent

local Active = false

tool.Activated:Connect(function()
	if Active == false then
		Active = true
		wait(1)
		h.Health = h.Health +25 
		wait(5)
		Active = false
	end
end)

1 answer

Issue

player.Character is nil

Solution

Short and lazy answer

Use this: local c = player.Character or player.CharacterAdded:Wait()

Explanation on why that works

player.Character might be nil because the player's Character does not exist yet. Since it does not exist yet we need to wait for it to exist. You can get the value returned from a signal when it fires by using the :Wait() method on it.

local c = player.CharacterAdded:Wait()

However now we run into the issue where the character exists and then c is just going to yield the thread.

So instead we can assign local c to be player.Character and if that is nil we can set it to be what player.CharacterAdded:Wait() returns

local c = player.Character

if (c == nil) then
	c = player.CharacterAdded:Wait()
end

However we can reduce the code using the or operator.

local c = player.Character or player.CharacterAdded:Wait()

This essentially sets c to be player.Character if player.Character is "truthy", however if it is not then it set it to the other side of the equation, player.CharacterAdded:Wait().

This can be generalized as a = b or c; if b is true then a becomes b, if b is false then a becomes c, if b and c are true then a becomes b, and if b and c are false a becomes c.

Resources:

https://nachtimwald.com/2019/02/20/lua-ternary/

http://lua-users.org/wiki/TernaryOperator

7 comments

0

Now I am getting 'Humanoid is not a valid member of Model' Saying that Humanoid is not a part of c, when it should.

0

c:WaitForChild("Humanoid") Maybe this work :/

0

@Block_manvn After changing that, I'm not getting any errors but I'm not getting healed either.

0

Is Humanoid MaxHealth is 100 and Humanoid Health right now is 100?

0

I set my Health to 1 with the MaxHealth at 100. I clicked with the tool and my health stayed the same. I'm not getting any errors.

0

Oh right, I forgot, you can't change Humanoid.Health by using LocalScript(mean from cilent). You should use RemoteEvent to make the Server change your Health.

0

Ah, right. Thank you.

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