Can someone help me cleanup my script?

My script already works, but i’m worried its done poorly and may lag the game. I was planning on using this same script multiple times in one game so I want it to be as smooth as possible

local camera = workspace.CurrentCamera
local Textlabel = script.Parent.TextLabel
local UIS = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer
local Torso = game.Workspace.NPCS.Test.Torso
local char = Player.Character or Player.CharacterAdded:Wait()
local HumanoidRootPart = char:WaitForChild("HumanoidRootPart")
local mouse = Player:GetMouse()
local debounce = true
local camera = game.Workspace.CurrentCamera

local function typewrite(object,Text)
	for i = 1, #Text,1 do
		object.Text = string.sub(Text,1,i)
		wait(0.05)
	end
end

UIS.MouseDeltaSensitivity = 1
script.Parent.TextButton.Visible = false
script.Parent.SecondButton.Visible = false

UIS.InputChanged:Connect(function()
	if mouse.Target:WaitForChild("Interact") then
		UIS.InputBegan:Connect(function(Input)
			if mouse.Target.Parent.Name == ("Test") then
				if Input.KeyCode == Enum.KeyCode.E then
					if debounce == true then
						debounce = false
						local Magnitude = (HumanoidRootPart.Position - Torso.Position).Magnitude
						if Magnitude <= 10 then
							UIS.MouseDeltaSensitivity = 0
							UIS.MouseIconEnabled = false
							HumanoidRootPart.Anchored = true
							script.Parent.Enabled = true
							typewrite(Textlabel, "Beep Beep Im a robot and im gonna steal your kidneys")
							wait(1)
							script.Parent.TextButton.Visible = true
							script.Parent.SecondButton.MouseButton1Down:Connect(function()
								script.Parent.SecondButton.Visible = false
								typewrite(Textlabel, "balls")
								wait(1)
								script.Parent.Enabled = false
								UIS.MouseBehavior = Enum.MouseBehavior.Default
								UIS.MouseDeltaSensitivity = 1
								UIS.MouseIconEnabled = true
							end)
							script.Parent.TextButton.MouseButton1Down:Connect(function()
								script.Parent.TextButton.Visible = false
								typewrite(Textlabel, "Im also gonna stab you and steal all your money")
								wait(1)
								script.Parent.SecondButton.Visible = true
								debounce = true
							end)

						end
					end
					
			end
			
			end
		end)

	else
		script.Parent.Enabled = false
		script.Parent.Parent.Interact.Enabled = false
		HumanoidRootPart.Anchored = false
	end
end)


I do not want you guys to rewrite the entire script, just tell me some tips on how to make it more clean.

1 Like

UIS.InputBegan will be connected multiple times, because it is Inside UIS.InputChanged, this will lag out the game the more you activate it.
Including this, from the 3 if statements you had you can make into only 1.

3 Likes

thank you i knew i did something wrong

1 Like