Feedback on my script

Hello, Im wondering if my code is optimised and good enough.
I’m fairly new to scripting (3 mo), so my code isnt exactly the best. Give your honest opinions on this script. Thanks!

local CollectionService = game:GetService("CollectionService")
local TweenService = game:GetService("TweenService")
local tag = "codedoor"
local waittime = 4.5

local taggedObjects = CollectionService:GetTagged(tag)

local function open(door)
	local tweenInfo = TweenInfo.new(1, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut)
	local goal = {Transparency = 1}
	local tween = TweenService:Create(door, tweenInfo, goal)
	
	tween:Play()
	
	tween.Completed:Connect(function()
		door.CanCollide = false
	end)
end

local function close(door)
	local closetweenInfo = TweenInfo.new(1, Enum.EasingStyle.Linear, Enum.EasingDirection.InOut)
	local closegoal = {Transparency = 0}
	local closetween = TweenService:Create(door, closetweenInfo, closegoal)

	closetween:Play()

	closetween.Completed:Connect(function()
		door.CanCollide = true
	end)
end

game.Players.PlayerAdded:Connect(function(player)
	player.Chatted:Connect(function(msg)
		for _, door in pairs(taggedObjects) do	
			local code = door:FindFirstChild("Code")
			
			if code and string.lower(msg) == string.lower(code.Value) then
				open(door)
				
				task.delay(waittime, function()
					close(door)
				end)
				
				print("Correct! The answer was: "..code.Value..".")
			else
				warn("Code not found / Incorrect code")
			end
		end
	end)
end)
1 Like

Hey there! Firstly, personally I would use a single function to change door status.

local doorState = false

local function changeDoorState(door)
    local tween -- same variable for tween's creation.

    if doorState then -- if doorState == true then door is open, we have to close it.
        Tween = TweenService:Create(door, TweenInfo, {Transparency = 0})
        -- close door tween
    else -- if doorState == false then door is closed, we have to open  it.
        Tween = TweenService:Create(door, TweenInfo, {Transparency = 0})
        -- open door tween
    end

    door.CanCollide = not door.CanCollide
    doorState = not doorState -- switch to inverse value of doorState
end
2 Likes

Thank you! I’ll give it a try!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.