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)
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)
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.