Parents and Children

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 this, you can use parent and child relationships with scripts. To practice this concept, you'll start with a single part that changes colors. Then, using a parent and child relationship, you'll make it so you can duplicate that part, allowing the code to be reusable.

Setting Up the Project and Script

This practice can be included in any blank template. For it, you'll just use any part and script.

  1. Create a new part and rename it. This lesson will use ColorPart.

  2. Right-click the part and select Insert Object > New Script. Rename the script, ColorChangeScript

  3. Copy and paste the code below into ColorChangeScript. This stores the part in a variable, then changes its color.


    local ColorPart = game.Workspace.ColorPart
    ColorPart.Color = Color3.fromRGB(50, 240, 255)
  4. Play the project to just check that the part changes color as desired.

Parent and Child Relationships

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 current script, you can only change the color of a single part named ColorPart. To change the color of any part, you can use a parent/child relationship. In code, this uses script.Parent, which gets whatever the object is attached to.

In this case, the script will get the parent part, allowing the code to be reusable in any part, regardless of name.

Using script.Parent

script.Parent can be assigned to a variable like any other value with the = symbol.

  1. In the ColorChangeScript, replace the named part with script.Parent. Check your code below.


    local ColorPart = script.Parent
    ColorPart.Color = Color3.fromRGB(50, 240, 255)

Testing Reusable 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. Right-click on the color part and select Duplicate, or use the hot-key CTRL/CMD + D. Create at least three total parts.

  2. Run the game to check that all parts changed color.

Why Use script.Parent

Notice here, you just changed the color of all these parts without specifically naming them. Imagine if you're a professional game developer in charge of coding an entire game environment with thousands of parts. Using code such as script.Parent will come in handy to make your code reusable.

Additionally, parent/child relationships are a concept that will come up often in computer science. For example, one advanced topic included object-oriented programming, which heavily relies on this idea.