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

How to check if parts are same colour?

Asked by 9 years ago

How would you check if 4 parts are the same colour, and if they are print 'similar'

2 answers

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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 A~B, B~C, 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
Ad
Log in to vote
-2
Answered by 9 years ago
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:

http://pastebin.com/y2mjRFgv

Answer this question