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

Why does error come eventhough script itself works fine?

When i made a kill block with script, the output executes error that says : 11:28:55.932 - Workspace.Basic traps and power ups tutorial.Trap.Script:7: attempt to index local 'humanoid' (a nil value).

However, the script itself works fine and it does make humanoid health to 0. Can someone help me to know what is the error with this script?

 local trapPart = script.Parent

local function onPartTouch(otherPart)

local partParent = otherPart.Parent

local humanoid = partParent:FindFirstChildWhichIsA("Humanoid")

if ( "humanoid" ) then

-- Set player's health to 0

humanoid.Health = 0

end

end

trapPart.Touched:Connect(onPartTouch)

3 answers

✓ Accepted answer

I believe you use the wrong syntax. In the if statement (Where it says if ("humanoid") then),the if statement is confirming the string: humanoid, not the variable: humanoid. Also, you do not need to use :FindFirstChildWhichIsA(), but it is totally up to you. Thus, the script would be:

Without :FindFirstChildWhichIsA()

 local trapPart = script.Parent
 local function onPartTouch(otherPart)
     local partParent = otherPart.Parent
     local humanoid = partParent:WaitForChild("Humanoid")
     if humanoid then -- Set player's health to 0
	     humanoid.Health = 0
     end
 end
 trapPart.Touched:Connect(onPartTouch)

With :FindFirstChildWhichIsA()

local trapPArt = script.Parent
local function onPartTouch(otherPart)
    local partParent = otherPart.Parent
    local humanoid = parentParent:FindFirstChildWhichIsA("Humanoid")
    if humanoid then -- Set player's health to 0
	    humanoid.Health = 0
    end
end

Accept my answer if it works for you!

Hi Yuuwa0519, the reason because your code don´t executes as well is because you are using a string as condition if ("humanoid") instead of if (humanoid).

Fix:

local Trap = script.Parent

Trap.Touched:Connect(function(instance)
	local Humanoid = instance.Parent:FindFirstChildWhichIsA("Humanoid")
	
	if Humanoid then
		Humanoid["Health"] = 0
	end
end)

2 comments

0

oh so i dont make the the if part to string, but just directly put in as variable?

0

yes

I believe you're not following the syntax of Roblox.

  local trapPart = script.Parent
    
    local function onPartTouch(otherPart)
    
    local partParent = otherPart.Parent
    
    local humanoid = 

partParent:FindFirstChildWhichIsA("Humanoid")
    
    if ( humanoid ) then
    
    -- Set player's health to 0
    
    humanoid.Health = 0
    
    end
    
    end
    
    trapPart.Touched:Connect(onPartTouch)

"humanoid" wouldn't work because that's a string. You want to check to see if the variable exists, not the string. So this should fix your issue.

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