How To Change A Part's Color When A Player Touches It In Roblox Studio
A beginner Roblox Studio lesson: use a Script and the Touched event so a part changes color when a player steps on it.
What You Will Build
In this lesson you will make a single part that turns green when a player's character touches it, then turns back to gray after two seconds. It is a small project, but it teaches the three ideas almost every Roblox game uses: finding an object from a script, listening for an event and changing a property.
Set Up The Part
Open Roblox Studio and create a new Baseplate place. On the Home tab, click Part to add a block, then use the Scale tool to make it a flat pad about eight studs wide. In the Properties window, tick Anchored so the pad does not fall or slide, and rename it TouchPad in the Explorer window so it is easy to find later.
Add The Script
Hover over TouchPad in the Explorer, click the plus button and choose Script. A Script placed inside a part runs on the server, so every player sees the same color. Delete the starter line and type the code below. The variable script.Parent points to the part that holds the script, which keeps the code working even if you rename the part later.
local pad = script.Parent
local debounce = false
pad.Touched:Connect(function(hit)
local humanoid = hit.Parent:FindFirstChildWhichIsA("Humanoid")
if humanoid and not debounce then
debounce = true
pad.BrickColor = BrickColor.new("Lime green")
task.wait(2)
pad.BrickColor = BrickColor.new("Medium stone grey")
debounce = false
end
end)How The Code Works
The Touched event fires every time anything bumps into the pad, including other parts, so the script first checks for a Humanoid, which only characters have. The debounce variable stops the event from running many times while the player stands on the pad. The task.wait function pauses for two seconds before the color goes back.
- Press Play and walk onto the pad to test it.
- Change the colors by editing the BrickColor names.
- Try changing Transparency or Material instead of color as a next step.
Common Problems And Fixes
If nothing happens when you step on the pad, open the Output window from the View tab and look for red error text. A message about script.Parent usually means the Script was placed in Workspace instead of inside TouchPad. If the color flickers rapidly, check that the debounce line is set back to false only after the wait. If the pad slides away when touched, the Anchored box was left unticked.