Why doesn't this script featuring else and if statements work?

I haven’t had much experience developing on Studio, but I made this simple script featured inside of a “ClickDetector” object, which is within a “Part.”
The purpose of this script is to make a basic door. If the door is opaque, then when you click it, it should disable collision. If the door is transparent, then when you click it, it should enable collision.

The issue is that the script works for the first time when the door is clicked once (no matter if the door starts with cancollide enabled or disabled). Whenever you try to click it again, nothing happens.

This is my most recent revision of the script. I’ve tried putting it within “while true do” statements and separating the if and elseif statements into two different scripts, to which the former crashed Studio and the latter gave me the same results as my original problem.
Once again, I’m basically a new developer so please put your language into ‘noob’ terms haha.

if script.Parent.Parent.CanCollide == true then
	script.Parent.MouseClick:Connect(function()
		script.Parent.Parent.Transparency = 1
		script.Parent.Parent.CanCollide = false
	end)

elseif script.Parent.Parent.CanCollide == false then
	script.Parent.MouseClick:Connect(function()
		script.Parent.Parent.Transparency = 0
		script.Parent.Parent.CanCollide = true
	end)
end

You are checking if the door is collidable when the game runs, and assign a single event based on the value

script.Parent.MouseClick:Connect(function()
if script.Parent.Parent.CanCollide == true then
		script.Parent.Parent.Transparency = 1
		script.Parent.Parent.CanCollide = false
elseif script.Parent.Parent.CanCollide == false then
	        script.Parent.Parent.Transparency = 0
		script.Parent.Parent.CanCollide = true
end
	end)

I see. So basically, having the “script.Parent.MouseClick:Connect(function()” outside of the if and elseif statements will ensure that the script doesn’t “confuse” itself because of multiple events, so instead we mash it into one?

Thanks so much by the way. I appreciate the help!

1 Like

image

In your code, either the red or the blue part will run because the script checks for the collision at the beginning of the code. If the cancollide is set to true when the game starts, only the red function will run

1 Like

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