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 2 years 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.

01game.workspace.r1.CanCollide = math.random(1,2) == 1
02if game.Workspace.r1.CanCollide ~= true then
03    game.Workspace.l1.CanCollide = false
04end
05game.workspace.r2.CanCollide = math.random(1,2) == 1
06if game.Workspace.r2.CanCollide ~= true then
07    game.Workspace.l2.CanCollide = false
08end
09game.workspace.r3.CanCollide = math.random(1,2) == 1
10if game.Workspace.r3.CanCollide ~= false then
11    game.Workspace.l3.CanCollide = false
12end
13game.workspace.r4.CanCollide = math.random(1,2) == 1
14if game.Workspace.r4.CanCollide ~= true then
15    game.Workspace.l4.CanCollide = false
View all 36 lines...

1 answer

Log in to vote
0
Answered by 2 years 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.

01-- initialise a new variable with the amount of parts inside workspace
02PARTS_COUNT: number = 9
03 
04-- create a for loop
05for index = 1, PARTS_COUNT do
06    -- define the two parts
07    local PartRight = workspace:WaitForChild('r' + index)
08    local PartLeft = workspace:WaitForChild('l' + index)
09    -- check if both parts exists, if not, skip this number
10    if PartRight == nil or PartLeft == nil then
11        continue
12    end
13    -- randomly generate the bool
14    -- we use (math.random(1, 2) - 1) because 0 is false, and 1 is true
15    local Enabled: bool = ((math.random(1, 2) - 1) == 1)
16    -- set PartRight's collision
17    PartRight.CanCollide = Enabled
18    -- call 'not Enabled' to give us the opposite (false will turn into true, and vice versa)
19    PartLeft.CanCollide = not Enabled
20end
Ad

Answer this question