Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Why does this random bool script not work? More details in text below.

Asked by 1 year ago

I want the right to be true, and the left to be false, or vice versa. All I get is both true, both false or sometimes it works.

game.workspace.r1.CanCollide = math.random(1,2) == 1
if game.Workspace.r1.CanCollide ~= true then 
    game.Workspace.l1.CanCollide = false
end
game.workspace.r2.CanCollide = math.random(1,2) == 1
if game.Workspace.r2.CanCollide ~= true then 
    game.Workspace.l2.CanCollide = false
end
game.workspace.r3.CanCollide = math.random(1,2) == 1
if game.Workspace.r3.CanCollide ~= false then 
    game.Workspace.l3.CanCollide = false
end
game.workspace.r4.CanCollide = math.random(1,2) == 1
if game.Workspace.r4.CanCollide ~= true then 
    game.Workspace.l4.CanCollide = false
end
game.workspace.r5.CanCollide = math.random(1,2) == 1
if game.Workspace.r5.CanCollide ~= true then 
    game.Workspace.l5.CanCollide = false
end
game.workspace.r6.CanCollide = math.random(1,2) == 1
if game.Workspace.r6.CanCollide ~= true then 
    game.Workspace.l6.CanCollide = false
end
game.workspace.r7.CanCollide = math.random(1,2) == 1
if game.Workspace.r7.CanCollide ~= true then 
    game.Workspace.l7.CanCollide = false
end
game.workspace.r8.CanCollide = math.random(1,2) == 1
if game.Workspace.r8.CanCollide ~= true then 
    game.Workspace.l8.CanCollide = false
end
game.workspace.r9.CanCollide = math.random(1,2) == 1
if game.Workspace.r9.CanCollide ~= true then 
    game.Workspace.l9.CanCollide = false
end

1 answer

Log in to vote
0
Answered by 1 year ago

There is a much more efficient way of completing this task, which also allows for expandability.

Explanations are left in comments inside the code chuck below.

-- initialise a new variable with the amount of parts inside workspace
PARTS_COUNT: number = 9

-- create a for loop
for index = 1, PARTS_COUNT do
    -- define the two parts
    local PartRight = workspace:WaitForChild('r' + index)
    local PartLeft = workspace:WaitForChild('l' + index)
    -- check if both parts exists, if not, skip this number
    if PartRight == nil or PartLeft == nil then
        continue
    end
    -- randomly generate the bool
    -- we use (math.random(1, 2) - 1) because 0 is false, and 1 is true
    local Enabled: bool = ((math.random(1, 2) - 1) == 1)
    -- set PartRight's collision
    PartRight.CanCollide = Enabled
    -- call 'not Enabled' to give us the opposite (false will turn into true, and vice versa)
    PartLeft.CanCollide = not Enabled
end
Ad

Answer this question