local Part = script.Parent Part.Touched:Connect(function(hit) wait(0.5) Part.Anchored = false end) wait(3) if Part.Anchored == false then print("Worked") wait(2) local Parte = Instance.new("Part", game.Workspace) Parte.Anchored = true Parte.Position = Vector3.new(-22, 1, 4) end
First of all, you should use code blocks. Like aazkao said, you need to put the code in between the ~~ lines after you click the blue Lua button.
Also, when you're defining a variable and won't use it elsewhere, you should put a local
before it.
You might not get what I mean by elsewhere, but you could always check the wiki to know what local variables and global variables are.
But for now, basically when you're defining a variable outside of any function or statement, you use local
.
local Part = script.Parent -- the local goes before the variable Part.Touched:Connect(function(hit) wait(0.5) Part.Anchored = false end) if Part.Anchored == false then print("Worked") wait(2) Parte = Instance.new("Part", game.Workspace) Parte.Anchored = true Parte.Position = Vector3.new(-22, 1, 4) end
Now, why this isn't working? A script goes from top to bottom extremely fast. the if
statement of yours won't work as when the if
statement is called, the Part's Anchored property is not false.
In other words, the if
statement is being called before the function that's supposed to make the Part's property to false is called.
To fix this, you can use a wait
statement to wait a few seconds before calling the if
statement.
local Part = script.Parent Part.Touched:Connect(function(hit) wait(0.5) Part.Anchored = false end) wait(3) -- waits 3 seconds if Part.Anchored == false then print("Worked") wait(2) Parte = Instance.new("Part", game.Workspace) Parte.Anchored = true Parte.Position = Vector3.new(-22, 1, 4) end
This will wait 3 seconds before the if
statement is called, therefore it will only print "Worked" if the Part's Anchored property is false after the script is ran.
You could also put it inside of a function and call that function when you want to. (Like the OnTouched event is only called when its part is touched.) Here's an example:
local Part = script.Parent local CD = Part:WaitForChild("ClickDetector") -- it waits until it finds "ClickDetector" inside of *Part*. Part.Touched:Connect(function(hit) wait(0.5) Part.Anchored = false end) CD.MouseClick:Connect(function() -- fires when CD (the ClickDetector) is clicked by a player. if Part.Anchored == false then print("Worked") wait(2) Parte = Instance.new("Part", game.Workspace) Parte.Anchored = true Parte.Position = Vector3.new(-22, 1, 4) end end)
In this example, there is a ClickDetector inside of Part. The script waits until it finds "ClickDetector" inside of Part. When the ClickDetector is clicked, it will fire a function that has your if
statement in.
When the Part's Anchored property is true when you click on the ClickDetector, it will print ("Worked").
I hope this helped in any way, I'm really not a good explainer. Thanks for reading.