Reusing Code with script.Parent

Reusing Code with script.Parent

The code you’ve used so far won’t run if there are multiple parts of the same name. That means if you want multiple parts to change colors, you’d have to make new parts and new scripts for each of them. That could take forever.

Instead of doing that, you can make a small change to the code that will let you copy and paste it into any part.

Attach a Script to a Part

Instead of creating a script in ServerScriptService, you’ll create a new script that’s attached to a part.

  1. Create a new part and rename it. This lesson will use LoopingPart.
  2. Right-click the part and select Insert Object > New Script.
  3. Rename the script. This lesson will use ColorChangeScript.
  4. In the script editor, delete print("Hello world!").
  5. Copy and paste the code below into ColorChangeScript. This creates a part that loops through a set of colors every three seconds.

Making the Script Reusable

With the current script, you can only change the color of a single part named LoopingPart. To change the color of any part, use script.Parent. This command stores whatever the object is attached to. In this case, the script is attached to a part.

  1. Replace local loopingPart = game.Workspace.LoopingPart with below:
local loopingPart = script.Parent

Parents and Children

A parent is anything that has objects, like scripts or parts, attached below it. Anything under the parent is its children. In the example shown below, ColorPart is the parent and ColorChangeScript is the child.

With the script and part just created, the part is the parent and the script is the child. This special line of code will tell the script to find it’s parent, the part. Using this line of code, you don’t even have to know what the part is named.

Duplicate and Test Parts

Now that the variable will refer to the whatever part the script is attached to, you can make as many copies as you want.

  1. Select the ColorPart in your game.
  2. Right-click the part and select copy, and then right-click again and select paste. You should end up with an exact duplicate of both the part and the script attached to it.
  3. Run the game to see the looping parts in action!

These documents are licensed by Roblox Corporation under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Roblox, Powering Imagination, and Robux are trademarks of Roblox Corporation, registered in the United States and other countries.