Search code examples
luaroblox

How to make a part change color between 2


I'm in Roblox and I wanna make a part change color randomly BUT, it only has two choices blue, or red. I only have

local block = script.parent
block.touched:Connect(function()
    block.brickcolor = math.random(brickcolor.red, brickcolor.blue)
end)

Solution

  • The easiest thing to do would be to define your colors, put them into an array, then use a random number to choose which index to pick :

    -- put the colors into an array of choices
    local colors = { BrickColor.Red(), BrickColor.Blue() }
    
    local block = script.parent
    block.Touched:Connect(function()
        -- pick a random index in the array
        local index = math.random(#colors)
    
        -- set the color
        block.BrickColor = colors[index]
    end)
    

    This format will work with any number of colors you add to the colors array. And if you want truly random numbers, feel free to add this to the top of the Script :

    math.randomseed(os.time())