Hello users, today i have a problem about scripts with “for”.
There is the scripts:
for v = 10,0,-1 do
if game.ReplicatedStorage.InGame.Value == false then
script.Parent.Text = "left "…v
if script.Parent.Text == “left 0” then
print(“good”)
game.ReplicatedStorage.InGame.Value = true
elseif game.ReplicatedStorage.InGame.Value == true then
print(“true”)
game.ReplicatedStorage.InGame.Value = false
end
end
end
The Bool Value (InGame) is set to “false” by default, but when InGame is set to “true” elseif doesn’t work. Any way to resolve this?
The reasoning is because the elseif statement is tied to the
statement rather than the
statement.
Reposition your ends to fix this.
Correct code:
for v = 10,0,-1 do
if game.ReplicatedStorage.InGame.Value == false then
script.Parent.Text = "left "…v
if script.Parent.Text == “left 0” then
print(“good”)
game.ReplicatedStorage.InGame.Value = true
end
elseif game.ReplicatedStorage.InGame.Value == true then
print(“true”)
game.ReplicatedStorage.InGame.Value = false
end
end
That’s because elseif is in the wrong scope. Here’s the fixed code
for v = 10,0,-1 do
if game.ReplicatedStorage.InGame.Value == false then
script.Parent.Text = "left " .. v
if script.Parent.Text == "left 0" then
print("good")
game.ReplicatedStorage.InGame.Value = true
end
elseif game.ReplicatedStorage.InGame.Value == true then
print("true")
game.ReplicatedStorage.InGame.Value = false
end
end
It is located in ReplicatedStorage, it is set to false by default, the script checks if it is false and returns to true but then the script does not seem to check whether it is true or not so that it is disabled again
That’s because in the last iteration of the loop, when v is equal to 0 the first condition is met, the value is set to true and the loop is finished, it doesn’t check the elseif condition because that’s how elseif works.
if condition1 then
-- 1
elseif condition2 then
-- 2
end
If condition1 is true, then it will not check condition2. You would have to do something like that:
for v = 10,0,-1 do
if game.ReplicatedStorage.InGame.Value == false then
script.Parent.Text = "left " .. v
if script.Parent.Text == "left 0" then
print("good")
game.ReplicatedStorage.InGame.Value = true
end
end
if game.ReplicatedStorage.InGame.Value == true then
print("true")
game.ReplicatedStorage.InGame.Value = false
end
end
Also, if you are doing that in a local script, then the changes won’t replicate to the server, but this script will work despite that. The only problem with the local script is that you won’t see the changes on the server and on other clients.