Hello, I’m trying to make a door which opens/closes on the click of a button. If the door is currently closed, then the click of the button will make it open, and vice versa (is the idea).
local door = script.Parent.Parent:FindFirstChild("Door")
local open = false
local function openAndClose()
if not open then
door.Transparency = 1
door.CanCollide = false
else
door.Transparency = 0
door.CanCollide = true
end
end
button.ClickDetector.MouseClick:Connect(openAndClose)```
It's not working. Any help?
Edit: I'm not sure why this is showing in code format
You didn’t set the open variable back to true upon activation oof
local door = script.Parent.Parent:FindFirstChild("Door")
local open = false
local function openAndClose()
if not open then
open = true
door.Transparency = 1
door.CanCollide = false
else
open = false
door.Transparency = 0
door.CanCollide = true
end
end
button.ClickDetector.MouseClick:Connect(openAndClose)
You have to end your code format with another ``` lol
I know you got your answer but I recommend you use the Tenary operator to help shorten your code around, with it, you can easily be turned into this
local door = script.Parent.Parent:FindFirstChild("Door")
local open = false
local function openAndClose()
door.Transparency = open and 0 or 1
door.CanCollide = open and true or false
open = not open
end
button.ClickDetector.MouseClick:Connect(openAndClose)
Basically you give it a condition and if that condition is true, what;'s after and will be set to the property/variable, and if the condition is false, it sets the property/varaible to what’s after or
Basically, the way you were doing your code could be simplified via the use of the Tenary operator. To give an example, let’s say you have a variable called result, which stores the highest number. You give it 2 numbers, x and y, you’d do
if x > y then
result = x
else
result = y
end
Or you could use the tenary operator
result = x > y and x or y
Which si exactly the same as that if-else statement. It’s just preference but it is nicer to use to reduce unneeded if statements
Glad to have taught you something new! I hope it will be able to reduce the amount of time you spend and what not!
Oh and since I didn’t mention it
open = not open
Basically just inverts the value of open
So if open was true, it’d be false afterwards and vice versa. I think I hopefully mentioned the correct usage of the and and or in that operator, if not, you could try to flip the 0 and 1 and the true and false!