I recently made a ray cast gun using the wiki tutorial but i noticed that it still shoots even after it has been unequipped. I also tried adding the Equipped and Unequipped functions but to no avail as it kept saying that mouse wasn't indexed or something like that. Can anyone help me figure out why this is happening?
local tool = script.Parent local Player = game:GetService("Players").LocalPlayer local Shooting = true local cooldown = 0.29 mouse_held = false mouse = Player:GetMouse() mouse.Button1Down:connect(function() if Shooting then Shooting = false mouse_held = true wait(0.29) repeat wait() local ray = Ray.new(tool.Handle.CFrame.p, (mouse.Hit.p - tool.Handle.CFrame.p).unit * 300) local part, position = workspace:FindPartOnRay(ray, Player.Character, false, true) local beam = Instance.new("Part", workspace) beam.BrickColor = BrickColor.new("Bright Yellow") beam.FormFactor = "Custom" beam.Material = "Neon" beam.Transparency = 0.25 beam.Anchored = true beam.Locked = true beam.CanCollide = false local distance = (tool.Handle.CFrame.p - position).magnitude beam.Size = Vector3.new(0.3, 0.3, distance) beam.CFrame = CFrame.new(tool.Handle.CFrame.p, position) * CFrame.new(0, 0, -distance / 2) --* CFrame.Angles(0,math.random(),0,0) game:GetService("Debris"):AddItem(beam, 0.1) if part then local humanoid = part.Parent:FindFirstChild("Humanoid") if not humanoid then humanoid = part.Parent.Parent:FindFirstChild("Humanoid") end if humanoid then humanoid:TakeDamage(15) end end wait(cooldown) Shooting = true until (mouse_held == false) end end) mouse.Button1Up:connect(function() mouse_held = false end)
You need to make a boolean variable that starts out as false. When the tool is equipped turn the variable true. When it is unequipped turn it to false. Create an if statement inside the mouse button event that checks to make sure the tool is equipped based on the variable.
There is no point using Player:GetMouse() when you can use the equipped function of the tool. Also, use the unequipped event to tell the gun to not be able to fire anymore.