Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do you make an if statement that triggers when a block changes to a certain color?

So basically I have an if statement, I want things to be triggered by it but I can't seem to find how. Here's what I wrote

if game.workspace.part.brickcolor == brickcolor.new("COLOR") 

2 answers

✓ Accepted answer

Pay attention to uppercase letters; Lua is case sensitive.

  • game.workspace should be game.Workspace (or simply workspace for short)
  • part presumptively should be Part
  • brickcolor and brickcolor.new() should become BrickColor and BrickColor.new()
  • Here is the list of all BrickColor codes (be sure to pay attention to capitalization)

Another issue with your code is you're forgetting your terminating operator, or end. Here's how an if statement should look:

if statement then
...
end

So, in your case it'd look like this:

if workspace.Part.BrickColor == BrickColor.new("Your colour") then
	-- do something
end

However, this may not work, since it's only checking at the beginning of the script. How do you fix this? You could loop indefinitely and constantly check:

while true do -- loops forever, since true is always equal to true
	if workspace.Part.BrickColor == BrickColor.new("Blah blah") then
		-- ...
	end
	wait() -- required for infinite loops, or your game will "hang"
end

However, Roblox supplies us with an easier and much more efficient way of doing this, using RBXScriptSignals. In this case you could use the GetPropertyChangedSignal method of the part to generate an event for when a property is updated, such as BrickColor. You can then Connect this event to a function that has your if statement.

local part = workspace.Part
part:GetPropertyChangedSignal("BrickColor"):Connect(function()
	if part.BrickColor == BrickColor.new("Eiffel tower") then
		-- finally do something here
	end
end)

If I helped, be sure to upvote/accept!

1 comment

0

One thing to note - you don't actually need to create a BrickColor object in order to run it against the part's BrickColor. You can run Part.BrickColor against a string "Eiffel tower" and get the same outcome.

--use the Changed event to see when a part's BrickColor changes

local part = game.Workspace.Part

local color = BrickColor.new("Lime green")

part.Changed:connect(function(prop)
	if prop == "BrickColor" then
		if part.BrickColor == color then
			print ("hello")
		end
	end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.