Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Simple if else switch - Probably easy solution?

Hi all, complete scripting newbie here, just trying to create a simple if else switch as my first test script, but the MouseClick only fires the 'OpenPortal' function. I am so new to this I'd imagine the solution is very simple but I'd appreciate any help!

local DoorCenter = script.Parent.DoorCenter
local DoorSwitch = script.Parent.DoorSwitch
local DoorClicker = script.Parent.DoorSwitch.ClickDetector

local function OpenPortal()
	DoorCenter.CanCollide = false
	DoorCenter.Transparency = 0.75
	DoorCenter.BrickColor = BrickColor.Green()
	print ("Door opened")
end
local function ClosePortal()
	DoorCenter.CanCollide = true
	DoorCenter.Transparency = 0
	DoorCenter.BrickColor = BrickColor.Red()
	print ("Door closed")
end

if DoorCenter.CanCollide == false then
	DoorClicker.MouseClick:connect(ClosePortal)
else
	DoorClicker.MouseClick:connect(OpenPortal)
end

1 answer

Use this way; it is a lot simpler:

local DoorCenter = script.Parent.DoorCenter
local DoorSwitch = script.Parent.DoorSwitch
local DoorClicker = script.Parent.DoorSwitch.ClickDetector
local open = DoorCenter.CanCollide

function SwitchPortal(player)
	open = not open
	DoorCenter.CanCollide = not open
	DoorCenter.Transparency = (open and 0.75) or 0
	DoorCenter.BrickColor = (open and BrickColor.Green()) or BrickColor.Red()
	print ("Door "..((open and "opened") or "closed"))
end

DoorClicker.MouseClick:Connect(SwitchPortal)

The reason your script doesn't work is that since CanCollide is set to true, it will only connect to the open function.

I would advise using the first method as it is a lot simpler and more efficient, but here is the solution in terms of your original script.

local DoorCenter = script.Parent.DoorCenter
local DoorSwitch = script.Parent.DoorSwitch
local DoorClicker = script.Parent.DoorSwitch.ClickDetector

local function OpenPortal()
	DoorCenter.CanCollide = false
	DoorCenter.Transparency = 0.75
	DoorCenter.BrickColor = BrickColor.Green()
	print ("Door opened")
end

local function ClosePortal()
	DoorCenter.CanCollide = true
	DoorCenter.Transparency = 0
	DoorCenter.BrickColor = BrickColor.Red()
	print ("Door closed")
end

DoorClicker.MouseClick:connect(function(player)
	if DoorCenter.CanCollide then
		OpenPortal()
	else
		ClosePortal()
	end
end)

1 comment

0

Thank you for the example and solution, this is great help. I see what I did.

This discussion is preserved as it was. New answers, comments, and votes are closed.