If statement not working

I am making a script that uses a if statement but it doesn’t work, all the code under the if will run even if not supposed to run
The Script:

UserInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.M then
		if Frame:GetAttribute("Open") == false then 
-- This is the first if that dosent work
			print("Open")
			Frame:SetAttribute("Open", true)
		game.Workspace.SoundFolder.phone_open:Play()
		Main.PhoneMain:TweenPosition(
			UDim2.new(0.006, 0,0.47, 0),
			"Out",
			"Quad",
			.2,
			true
		)	
		end
		if Frame:GetAttribute("Open") == true then
-- This is the if that also dosent work
			print("Close")
			Frame:SetAttribute("Open", false)
			game.Workspace.SoundFolder.phone_close:Play()
			Main.PhoneMain:TweenPosition(
				UDim2.new(0.006, 0,0.988, 0),
				"Out",
				"Quad",
				.2,
				true
			)	
		end
		end
		
end)

Could you elaborate on what you mean by “runs if not supposed to run”?

1 Like

Here you go, read the comments to know what changed.

UserInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.M then
		if not Frame:GetAttribute("Open") then 
			-- The previous one didn't work because "Open" didn't exist, so it was "nil" not "false"
			print("Open")
			Frame:SetAttribute("Open", true)
			game.Workspace.SoundFolder.phone_open:Play()
			Main.PhoneMain:TweenPosition(
				UDim2.new(0.006, 0,0.47, 0),
				"Out",
				"Quad",
				.2,
				true
			)	
		elseif Frame:GetAttribute("Open") == true then
			-- Changed to elseif because this would run right after the other one, effectively locking it closed otherwise.
			-- This will work now.
			print("Close")
			Frame:SetAttribute("Open", false)
			game.Workspace.SoundFolder.phone_close:Play()
			Main.PhoneMain:TweenPosition(
				UDim2.new(0.006, 0,0.988, 0),
				"Out",
				"Quad",
				.2,
				true
			)
		end
	end
end)
2 Likes

Also, this can be shortened by using if expressions:

UserInputService.InputBegan:Connect(function(input)
    if input.KeyCode ~= Enum.KeyCode.M then
        return
    end
    -- Note that if the attribute is nil, the not operation will still result in true
    local newState = not Frame:GetAttribute("Open")
    Frame:SetAttribute("Open", newState)
    game.Workspace.SoundFolder["phone_" .. if newState then "open" else "close"]:Play()
    Main.PhoneMain:TweenPosition(
        UDim2.fromScale(0.006, if newState then 0.47 else 0.988),
        Enum.EasingDirection.Out,
        Enum.EasingStyle.Quad,
        0.2,
        true
    )
end)
if Frame:GetAttribute("Open") then
	--Do code.
else
	--Do other code.
end