Part.OnTouched function doesn't work, in what could be the problem?

Script should check if player is a owner of the mortar. Simply, owner value inside of the model already has player username. However, script just stops running before checking it.

local mortar = script.Parent
local touch = mortar.Base.Part
local owner = mortar.Owner.Value

touch.Touched:Connect(function(player)
	print("1") -- here it stops
	if owner == player.Name then -- not running that part with no errors
		print("2")
		mortar:Destroy()
	end
end)

Does the part have CanTouch to true? Also, a touched event does not return a player, it returns the part that touched it.

Yeah, part has CanTouch set to true. So how I can get player then?

Get an ancestor model from otherpart:FindFirstAncesstorOfClass(“Model”) and then use Players | Roblox Creator Documentation to see if it’s a player’s character.

1 Like

.Touched returns the name of the part that touched it, not the player.

Move the owner variable into the touched function. We do this because when you run the game it’s automatically going to be set to nil or basically nothing. So it’s basically saying if “nothing” == to player.name then. If we put it inside the function, it will check when there is a player if not the owner variable will equal nothing.

Next, consider making a variable in the function called player and changing the “player” in the function parameters to “part”. Inside the variable write:

part.Parent:FindFirstChild(“Humanoid”)

this will check if the thing is a character. Change the if statement to this:

if owner == part.Parent.Name and player then --- player = if a humanoid was found.

Heres what the finished code should look like:


local mortar = script.Parent
local touch = mortar.Base.Part

touch.Touched:Connect(function(part)
    local owner = mortar.Owner.Value
    local player = part.Parent:FindFirstChild("Humanoid")
	print("1") 
	if owner == part.Parent.Name and player then 
		print("Worked")
		mortar:Destroy()
else
      Warn("Didn't Work")
	end
end)

I didn’t test this so not sure if its going to work, but I’m positive its gonna work.
Not sure if my explanation was clear it was kind of hard to explain.

: D

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.