I'm trying to get this to change a part's color to red or white, depending on what math.random selects (1 for red, 2 for white). The code basically works. However, the function seemingly never gets called, and the part changes to and remains black.
function light() local nl = Instance.new("PointLight", workspace) nl.Parent = script.Parent nl.Color = script.Parent.Color nl.Brightness = 2 end while true do wait(1) num = math.random(1,2) if num == 1 then script.Parent.Color = Color3.new(255, 0, 0) elseif num == 2 then script.Parent.Color = Color3.new(248, 248, 248) end end light()
The function is never called because the script is stuck on the while loop, code is read from up to down, it never reads the calling part because its looping over and over again in the while loop, to fix this put the part where your calling the function before the loop
function light() local nl = Instance.new("PointLight", workspace) nl.Parent = script.Parent nl.Color = script.Parent.Color nl.Brightness = 2 end light() while true do wait(1) num = math.random(1,2) if num == 1 then script.Parent.Color = Color3.new(255, 0, 0) elseif num == 2 then script.Parent.Color = Color3.new(248, 248, 248) end end
function light() local nl = Instance.new("PointLight") -- I removed the workspace modifier. Try not to use this when creating instances. Causes lag. nl.Parent = script.Parent -- this is the proper way to parent an instance. nl.Color = script.Parent.Color nl.Parent.Changed:connect(function(stat) -- added a function in the light to update its color if stat == "BrickColor" or stat == "Color" then -- make sure the color was what changed nl.Color = nl.Parent.Cololr end end) nl.Brightness = 2 end light() while true do wait(1) num = math.random(1,2) if num == 1 then script.Parent.Color = Color3.new(255, 0, 0) elseif num == 2 then script.Parent.Color = Color3.new(248, 248, 248) end end