How would I run a script only when a tool is activated?

I’m trying to make a mining system, and so I’d like to know how I can make it so that a script is only active when it detects that a tool is activated. If it makes it easier, I already have an attribute changing to “Activated” when activated, and “Deactivated” when deactivated. Below you’ll find the code that I’m looking to change.

local AzureOre = script.Parent
local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Hitbox = script.Parent:WaitForChild("Hitbox")
local replicatedStorage = game:GetService("ReplicatedStorage")
local OreTouchedEvent = replicatedStorage.OreTouchedEvent
local Character = Player.Character or Player.CharacterAdded:Wait()
local Pickaxe = Character:WaitForChild("Pickaxe")
local Handle = Pickaxe:WaitForChild("Handle")
local Count = 0


Hitbox.Touched:Connect(function(player)
	local function Check()			
		Count += 1
		local Cast = workspace:Raycast(Handle.Position, Handle.CFrame.LookVector * 2)
		if Cast then
			if Cast.Instance.Name ~= AzureOre.Name then return end
		else
			return
		end
	end

	repeat task.wait(1) Check() until Count == 5
	OreTouchedEvent:FireServer(AzureOre)
	Count = 0
	
end)
3 Likes

You could use the Tool.Activated and Tool.Deactivated events

1 Like

I have already done so within the scripts of the tool

local Tool = script.Parent
local Handle = Tool.Handle

Tool.Activated:Connect(function()
	Handle:SetAttribute("Activated")
end)

Tool.Deactivated:Connect(function()
	Handle:SetAttribute("Deactivated")
	wait(3)
end)
1 Like

What I wish to do is use the attribute that was set within the tool, outside of the tool within a localscript, to make the localscript only run if the tool is activated.

1 Like

I’m still looking for a possible answer, since I am very close to finishing the system.

1 Like

First off make sure you have only one attribute for activation and deactivated and make sure the attribute your setting is a bool value. You’re also missing the 2nd parameter in the function SetAttribute(), which is the value you would want to set. You might want to do something like this

local Tool = script.Parent
local Handle = Tool.Handle

Tool.Activated:Connect(function()
	Handle:SetAttribute("Activated", true)
end)

Tool.Deactivated:Connect(function()
	Handle:SetAttribute("Activated", false)
	wait(3)
end)

Then for making the local script only run if the tool is activated, you can just check if the attribute “activated” is true and if it is the code will run.

if handle:GetAttribute("Activated") == true then
   -- run the rest of the local script
end
1 Like