How would you check if 4 parts are the same colour, and if they are print 'similar'
✓ ANSWER ACCEPTED
How to check if parts are same colour?
2 answers
✓ Accepted answer
The BrickColor property is a BrickColor referencing the color of the part. They can be compared using ==. If we had 4 parts, A, B, C, and D, then we would compare their colors like this:
if A.BrickColor == B.BrickColor
and A.BrickColor == C.BrickColor
and A.BrickColor == D.BrickColor
then
-- Do whatever conditionally
end
(Other comparisons like AB, BC, C~D also works)
This isn't a very elegant solution, though. If you wanted a more robust solution, we would probably define this as a function:
function sameColor(A,B)
return A.BrickColor == B.BrickColor;
end
if sameColor(A,B) and sameColor(A,C)
and sameColor(A,D) then
-- Do whatever conditionally
end
We could do even better by allowing sameColor to take a list of parts as a parameter:
function sameColor(A,B)
if not B then
local allSoFar = true;
for _,part in ipairs(A) do
allSoFar = allSoFar and sameColor(A[1],part);
end
return allSoFar;
end
return A.BrickColor == B.BrickColor;
end
if sameColor({A,B,C,D}) then
-- Do whatever conditionally
end
We could also use Lua's n-ary functions to make this more elegant:
function sameColor(A,...)
local allSoFarSame = true;
local t = {...};
for i = 1,#t do
allSoFarSame = allSoFarSame and (A.BrickColor == t[i].BrickColor);
end
return allSoFarSame;
end
if sameColor(A,B,C,D) then
-- Do whatever conditionally
end
part1 = game.Workspace.part1
part2 = game.Workspace.part2
part3 = game.Workspace.part3
part4 = game.Workspace.part4
if part1.Color == Red and part2.Color == Red and part3.Color == Red and Part4.Color == Red then
-- code here
end
I would have this code look better but the forums have a weird box limit, if you want the text to be indented etc then go here:
This discussion is preserved as it was. New answers, comments, and votes are closed.
