Convert my script into tool.Activated

I made a script blah blah blah. I want to know how to convert it into a tool so when The player clicks. Tool. Activated runs the script. Problem is that my script runs when the player joins the game. I want it also to run when the player Uses the Tool. Activated. Here is the script I’m trying to convert into Tool.Activated:

function childAdded(child)
	if game.Players:FindFirstChild(child.Name) ~= nil then
		wait(1)
		local character = child
		local torso = child:findFirstChild("Torso")
		
		local insertedpart = Instance.new("Part")
		insertedpart.Name = "TorsoWeldingPart"
		insertedpart.CanCollide = false
		insertedpart.Size = Vector3.new(2,2,1)
		insertedpart.CFrame = torso.CFrame * CFrame.new(0,0.4,-0.5)
		insertedpart.Parent = character
		
		local mesh = Instance.new("SpecialMesh")
		mesh.Name = "PartMesh"
		mesh.MeshId = "rbxassetid://6850514697"
		mesh.Parent = insertedpart
		mesh.Scale = Vector3.new(0.9, 0.9, 0.9)
		mesh.TextureId = "rbxassetid://6850896431"
		
		local weld = Instance.new("Weld")
		weld.Name = "TorsoWeld"
		weld.Part0 = torso
		weld.C0 = torso.CFrame:inverse()
		weld.Part1 = insertedpart
		weld.C1 = insertedpart.CFrame:inverse()
		weld.Parent = insertedpart
		
		insertedpart.Anchored = false
		

	end
end

game.Workspace.ChildAdded:connect(childAdded)

Problem is that it uses ChildAdded so how can I make it run when Tool.Activated fires?!?

If you put the script inside the tool, you can just do

script.Parent.Activated:Connect(function()
-- code to execute when tool is activated
...
end)
1 Like

Problem is that it uses ChildAdded so how can I make it run when Tool.Activated fires?!?

It doesnt work if I remove the ChildAdded statement

I believe you are approaching this problem incorrectly.

First, there is a service in roblox called StarterPack that automatically gives tools to players that spawn in. You can make your tool first in roblox before any scripting (look up a YouTube video and learn about Handles).

Once done, add a LocalScript inside the Tool and connect it to .Activated like so:

local tool = script.Parent

tool.Activated:Connect(function()
    -- Your function
end)

I see, I misunderstood your question. You need to add the parts that you created to a tool instance. Tool instances that are children of character are registered as equipped.

local tool = Instance.new("Tool")
insertedpart.Parent = tool
tool.Parent = character

tool.Activated:Connect(function()
...
end)