Help Wanted for my gun script - urgent

Whenever the tool is clicked, I want to make it so it fires / stops firing regarding the state, but the gun wont stop firing.

local function fireWeapon()
        shooting = not shooting
	while shooting do
		if ammo > 0 and reloading == false then
			local mouseLocation = getWorldMousePosition()

			ammo = ammo - 1

			-- Calculate a normalised direction vector and multiply by laser distance
			local targetDirection = (mouseLocation - tool.Handle.Position).Unit

			-- The direction to fire the weapon, multiplied by a maximum distance
			local directionVector = targetDirection * MAX_LASER_DISTANCE

			-- Ignore the player's character to prevent them from damaging themselves
			local weaponRaycastParams = RaycastParams.new()
			weaponRaycastParams.FilterDescendantsInstances = {Players.LocalPlayer.Character}
			local weaponRaycastResult = workspace:Raycast(tool.Handle.Position, directionVector, weaponRaycastParams)

			-- Check if any objects were hit between the start and end position
			local hitPosition
			if weaponRaycastResult then
				hitPosition = weaponRaycastResult.Position

				-- The instance hit will be a child of a character model
				-- If a humanoid is found in the model then it's likely a player's character
				local characterModel = weaponRaycastResult.Instance:FindFirstAncestorOfClass("Model")
				if characterModel then
					local humanoid = characterModel:FindFirstChild("Humanoid")
					if humanoid then
						eventsFolder.DamageCharacter:FireServer(characterModel, hitPosition)
					end
				end
			else
				-- Calculate the end position based on maximum laser distance
				hitPosition = tool.Handle.Position + directionVector
			end

			timeOfPreviousShot = tick()

			eventsFolder.LaserFired:FireServer(hitPosition)
			LaserRenderer.createLaser(tool.Handle, hitPosition)

			local pgui = game.Players.LocalPlayer:FindFirstChild("PlayerGui")
			local ammogui = pgui.AmmoGUI

			local label = ammogui:FindFirstChild("AmmoCounter")
			label.Text = ammo .. " / " .. max_ammo

		elseif ammo <= 0 and reloading == false then
			local reload_sound = script.Parent.Handle.Reload
			print("reloading...")
			reloading = true
			reload_sound:Play()
			task.wait(1)
			ammo = max_ammo
			reloading = false

			local pgui = game.Players.LocalPlayer:FindFirstChild("PlayerGui")
			local ammogui = pgui.AmmoGUI

			local label = ammogui:FindFirstChild("AmmoCounter")
			label.Text = ammo .. " / " .. max_ammo
		end
		task.wait(FIRE_RATE)
	end
end

here’s the script, hope anyone can help

3 Likes

maybe try putting the while loop outside the function.

1 Like