How could i improve my Grabbing script?

Include a standalone, bare-bones rbxl file with only the code you want reviewed.

  • Code Review is for reviewing specific parts of your code, and not your whole game.
  • Code Review is intended for improving already-working code. If you need help debugging your code, please use Scripting Support.

Provide an overview of:

  • What does the code do and what are you not satisfied with?
  • What potential improvements have you considered?
  • How (specifically) do you want to improve the code?
-- Created 07/12/22 
local Box = script.Parent
local ClickDector = Box.ClickDetector
local Clicks = 0
local Weld = Instance.new("Weld")

ClickDector.MouseClick:Connect(function(Player)
	Clicks += 1
	print(Clicks)
	if Clicks == 1 then
		print("Player is holding the Box!")
		local Character = Player.Character or Player.CharacterAdded:Wait()
		local RightHand = Character:FindFirstChild("RightHand")
		Weld.Parent = script.Parent
		Weld.Part1 = script.Parent
		Weld.Part0 = RightHand
	elseif Clicks == 2 then
		Weld.Parent = nil
		print("The Player is no longer holding the Box")
			Clicks = 0
		end
	-- Fire the Clicked Event again to unweld from the character
end)

Hello, i’m looking for improvement with my current code because i’m not satisfied with how i’m using number values to handle the issue instead of a boolean i’m looking for improvement with booleans instead of numbers any help here would be appreciated :smiley:

Try using a proximity prompt, also here is an example for using a boolean.

local Box = script.Parent
local ClickDector = Box.ClickDetector
local Clicks = false
local Weld = Instance.new(“Weld”)

ClickDector.MouseClick:Connect(function(Player)
Clicks = not Clicks
print(Clicks)
if Clicks then
print(“Player is holding the Box!”)
local Character = Player.Character or Player.CharacterAdded:Wait()
local RightHand = Character:FindFirstChild(“RightHand”)
Weld.Parent = script.Parent
Weld.Part1 = script.Parent
Weld.Part0 = RightHand
else
Weld.Parent = nil
end)

this wat i would do

-- Created 07/12/22 
local Box = script.Parent
local ClickDector = Box.ClickDetector
local Clicked = false
local Weld = Instance.new("Weld")

ClickDector.MouseClick:Connect(function(Player)
	if Clicked == false then
		local Character = Player.Character or Player.CharacterAdded:Wait()
		local RightHand = Character:FindFirstChild("RightHand")
		Weld.Parent = script.Parent
		Weld.Part1 = script.Parent
		Weld.Part0 = RightHand
		Clicked = true
	elseif Clicked == true then
		Weld.Parent = nil
		Clicked = false
	end
	-- Fire the Clicked Event again to unweld from the character
end)