Issue with checking if something exists

Basically what im trying to do is check if this rock is touching something that has humanoid has one of its children. If it doesn’t have it, then it simply prints that its not a player in game

local rock = game.Workspace:FindFirstChild("ThickThing")
rock.Touched:Connect(
    function()
        local Human = rock.Touched
        if not Human.Humanoid then
            print("no humanoid detected! Stopping...")
        elseif Human.Humanoid then
            Human.Humanoid:TakeDamage(math.huge)
            end
    end
)

FindFirstChild is the function to use to check for the existence of an instance. Additionally Touched will pass the part that physically intersected the one you’re connecting the function on so you should be checking that part’s parent for the Humanoid instead of making the variable point at the event.

rock.Touched:Connect(function (hit)
    local hitParent = hit.Parent
    local humanoid = hitParent:FindFirstChild("Humanoid")
    -- Take damage if there's a humanoid

Do be wary of nested parts since they can also trigger Touched events if CanTouch is true, so for example a player character’s accessory handle may touch the rock but there’s no Humanoid in accessories so the player won’t take damage in that case.

2 Likes
local Players = game:GetService("Players")
local ThickThing = workspace.ThickThing
local Huge = math.huge

local function OnThickThingTouched(Hit)
	local HitModel = Hit:FindFirstAncestorOfClass("Model")
	if HitModel then
		local HitHumanoid = HitModel:FindFirstChildOfClass("Humanoid")
		if HitHumanoid then
			HitHumanoid:TakeDamage(Huge)
		end
	end
end

ThickThing.Touched:Connect(OnThickThingTouched)

With this implementation if the “Touched” event is fired resulting from the trigger part being touched by one or more of the player’s character’s accessories (which contain a BasePart instance named “Handle”) the connected function will still execute fully and correctly locate the “Humanoid” instance inside the character such that it can be dealt damage.