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

How would you get the character that touches a part?

Hello. So if I have a simple touched script like so:

local part = script.parent
part.Touched:Connect(function(hit)
	local char = hit.Parent:FindFirstChild("Humanoid")
	if char ~= nil then
		--do stuff
	end
end)

What I'm trying to do is find the character no matter what the part touches. The "character" I'm looking for is a mob so I can't just check if it's in the players list.

So my question is how can I change this to always find the character that hit the part?

5 comments

0

You could change it's humanoid name to something besides humanoid, and find if the hit's humanoid name is what you changed it to.

0

welp, the hit is always one of the player's bodyparts, and always his feet, and the bodyparts are parented to the character, so simply: hit.Parent

0

or is that not waht you want?

0

Well the way I have the part set up it can also hit hats and other things on the character. So sometimes it doesn't get the character. Is there any other method that would do it accurately?

0

Find if it hits a Humanoid

3 answers

check if the Model has Humanoid like :

if Hit.Parent:FindFirstChildOfClass("Humanoid") ~= nil then ... end

this will find the humanoid even if his name is changed, and doesn't will work with normal bricks, only Models with Humanoids like Mobs and Players

2 comments

0

I've tried this too but the problem is if it hits something like a hat. Then it would have to do Hit.Parent.Parent to get the humanoid. What I'm looking for is a way to check all possibilities.

0

you could use "or", for example : if Hit.Parent:FindFirstChildOfClass("Humanoid") ~= nil or Hit.Parent.Parent:FindFirstChildOfClass("Humanoid") then ... end

Here is another way you could do this:

if game.Players:GetPlayerFromCharacter(hit.Parent) then

GetPlayerFromCharacter() returns the player associated with the given character (assuming that the player is associated with that character). If the player is not associated with the given character, GetPlayerFromCharacter() will return nil.

1 comment

0

This would work but in my original question I say, " ...is a mob so I can’t just check if it’s in the players list". Therefore I can't get the player of a mob.

	local function onTouched(hit)
		local char = hit.Parent
		if char then
			if char ~= nil then
				--do the stuff
			end
		end
	end)

script.Parent.Touched:Connect(onTouched)

1 comment

0

by the way you forgot to call the function

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