Door script with handle

--[[
 _____  _            ____               _             ____               
|_   _|| |__    ___ / ___|   __ _  ___ | |__    __ _ |  _ \   ___ __   __
  | |  | '_ \  / _ \\___ \  / _` |/ __|| '_ \  / _` || | | | / _ \\ \ / /
  | |  | | | ||  __/ ___) || (_| |\__ \| | | || (_| || |_| ||  __/ \ V / 
  |_|  |_| |_| \___||____/  \__,_||___/|_| |_| \__,_||____/  \___|  \_/  
]]

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local workspace = game:GetService("Workspace")
local Zone = require(script:WaitForChild("Zone"))
local container = script.Parent
local zone = Zone.new(container)
local dooor = script.Parent.Parent

zone:setAccuracy(Zone.enum.Accuracy.High)

local function onPlayerEntered(player)
	local character = player.Character
	if not character then
		return
	end
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if not humanoid then
		return
	end
	if humanoid:GetAttribute("IKInProgress") then
		return
	end

	humanoid:SetAttribute("IKInProgress", true)
	local ikControl = humanoid:FindFirstChildOfClass("IKControl") or Instance.new("IKControl")
	if not ikControl:IsA("IKControl") then
		humanoid:SetAttribute("IKInProgress", false)
		return
	end

	ikControl.Weight = 1
	if not ikControl.Parent then
		ikControl.Parent = humanoid
		ikControl.Type = Enum.IKControlType.Position
		local leftHand = character:FindFirstChild("LeftHand")
		local leftUpperArm = character:FindFirstChild("LeftUpperArm")
		if not (leftHand and leftUpperArm) then
			humanoid:SetAttribute("IKInProgress", false)
			ikControl:Destroy()
			return
		end
		ikControl.EndEffector = leftHand
		ikControl.ChainRoot = leftUpperArm
	end

	local doorBaseAttachment = dooor and dooor:FindFirstChild("Base") and dooor.Base:FindFirstChild("Attachment")
	if not doorBaseAttachment then
		humanoid:SetAttribute("IKInProgress", false)
		return
	end

	ikControl.Enabled = true
	ikControl.Target = doorBaseAttachment
end

local function onPlayerExited(player)
	local character = player.Character
	if not character then
		return
	end
	local humanoid = character:FindFirstChildOfClass("Humanoid")
	if not humanoid then
		return
	end
	local ikControl = humanoid:FindFirstChildOfClass("IKControl") or Instance.new("IKControl")
	if not ikControl:IsA("IKControl") then
		humanoid:SetAttribute("IKInProgress", false)
		return
	end
	ikControl.Weight = 0
	task.wait(0.2)
	ikControl.Enabled = false
	ikControl.Target = nil
	humanoid:SetAttribute("IKInProgress", false)
end

zone.playerExited:Connect(onPlayerExited)
zone.playerEntered:Connect(onPlayerEntered)

Please advise me how I can improve or optimise this code.

1 Like
  1. You’re using Instance:FindFirstChildOfClass to get the Humanoid, which is unnecessary
  2. You’re performing redundant checks (unnecessary IsA call)
  3. I’ve never used Zone but I’m pretty sure that to enter the zone you should already have your character loaded
1 Like

Thanks for your review! It is very helpful, I fixed everything you said.