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

Gun still shoots even after it has been Unequipped?

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)
			

3 answers

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.

2 comments

0

Using the equipped and unequipped events just brings up the errors, " attempt to index local 'mouse' (a nil value)" and "This mouse is no longer active".

0

Well, then you are probably doing it wrong.

You are using mouse.Button1Down so whenever someone clicks it shoots, Roblox has a way to go around using Button1Down and without checking if the tool is equipped or not.

-- Replace mouse.Button1Down:connect(function()
-- to  tool.Activated:connect(function()

More info here.

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