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

How do I change this from ClickDetector to onTouched?

Hello! So I have this script to where when I click a certain part, that part that I click will be destroyed, and I will have the tool in my inventory. What I am needing is from it to be changed from being a click detector script, to an on touched script. Where instead of it being clicked, all I need is for it to be touched. I want the same stuff to happen, just changing on how to obtain the tool. Here is the script:

script.Parent.ClickDetector.MouseClick:connect(function(plr)
	if plr.Backpack:FindFirstChild("Brick") then
	else
		local clone = game.Lighting.Brick:Clone()
		clone.Parent = plr.Backpack
		script.Parent:Destroy()
	end
end)

1 answer

Make the event 'script.Parent.Touched'. The part being touched is whatever part the click detector is inside of. The hit variable inside the touch event is the part that is currently touching the part we just mentioned. If the player touches the part, then the the player's foot, arm, head, etc is the hit variable. Since the leg/arm/foot etc is inside the player's character, hit.Parent.Name will give us the player's name. if we want to get the player object we'd say:

game:GetService("Players"):FindFirstChild(hit.Parent.Name)

The whole code would be:

script.Parent.Touched:Connect(function(hit)
	local player = game:GetService("Players"):FindFirstChild(hit.Parent.Name)
	
	--if the player exists, run the following code 
	if(player)then
		if player.Backpack:FindFirstChild("Brick") then
			--TODO: DO SOMETHING HERE
		else
        		local clone = game:GetService("Lighting").Brick:Clone()
        		clone.Parent = player.Backpack
       			script.Parent:Destroy()
		end
	end
end)

6 comments

0

What does the --TODO: DO SOMETHING HERE mean?

0

sorry shouldve clarified. you have an if statement that when the condition is true, it doesn't do anything. if you want to do something when the script finds a Brick in the backpack, write it on the line that says TODO: did you manage to get the script work alright?

0

^^ Use :GetService for Lighting

0

I believe that it will still throw an error if im not wrong.

0

Yes, this will throw an error. 'plr' does not refer to a player, it refers to the part that touched the part firing the event. Use GetPlayerFromCharacter(part.Parent) to acquire the player (if it exists).

0

didn't catch that. i'll make sure to update

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