Can this code be improved?

Hello. I made a carry tool for my game, and I feel like it can be improved. Here’s the tool in action:


Here’s the server script (there were no comments, I added them for clarity):
local prevname
local part
script.Parent.RemoteEvent.OnServerEvent:Connect(function(plr, obj)
	if obj and obj.Parent ~= workspace then
		plr:Kick("Do not cheat.") --Prevent players from spawning objects from ServerStorage
	else
		if obj then
			prevname = obj.Name
			obj.Name = "Handle"
			obj.Parent = script.Parent
			part = obj --Used when dropping the tool
			plr.Character.Humanoid:UnequipTools()
			plr.Character.Humanoid:EquipTool(script.Parent) --Handle doesn't attach to character's arm without this
		else
			part.Name = prevname
			part.Parent = workspace
			part.CanCollide = true
			plr.Character.Humanoid:UnequipTools() --Else the script breaks
		end
	end
end)

And here’s the client script:

local sel = Instance.new("SelectionBox")
sel.Parent = script.Parent
local mode = "none"
script.Parent.Equipped:Connect(function(mouse)
	m = mouse
	if mode ~= "carrying" then
	mode = "seeking"
	repeat
		if mouse.Target then
		if mouse.Target.Transparency == 1 then
			mouse.TargetFilter = mouse.Target --To ignore triggers
		end
		if mouse.Target:FindFirstChild("BoxType") and mouse.Target.Name ~= "Handle" then 
--[[BoxType is used internally in the game.
We check if the part's name is not "Handle" so we can't carry a box that is carried already.]]--
			sel.Adornee = mouse.Target
			mouse.Icon = "rbxasset://textures/DragCursor.png"
			mode = "selecting"
		else
			mouse.Icon = "rbxasset://textures/ArrowCursor.png"
			sel.Adornee = nil
			mode = "seeking"
		end
		end
		wait(0.1)
	until mode == "carrying" or mode == "none"
	end
end)
script.Parent.Activated:Connect(function()
	if mode == "selecting" then --We pick up the selected box
		script.Parent.RemoteEvent:FireServer(m.Target)
		sel.Adornee = nil
		mode = "carrying"
		m.Icon = "rbxasset://textures/ArrowCursor.png"
	elseif mode == "carrying" then --We drop the box now
		script.Parent.RemoteEvent:FireServer()
		mode = "none"
	end
end)
script.Parent.Unequipped:Connect(function()
	if mode == "seeking" then
		mode = "none" --To prevent the script from working after the tool is unequipped
	end
end)
2 Likes

I don’t believe that you need to. But you can change the carrying animation.
Also, I think it can. It’s your choice.

3 Likes