Copying Code to Other Parts

Copying Code to Other Parts

This script is designed to work with any part it is added to. That means we can copy this script from the cube to something more dangerous looking like this pile of rubble which is named DangerTrap in game.

  1. In the Explorer, right-click TrapPartScript.
  2. Select Copy.
  3. In the game window, select DangerTrap (the pile of rubble).
  4. Right-click on DangerTrap and select Paste Into.
  5. Test the new trap to see that it hurts you.

In the script is the line local harmOrHealPart = script.Parent

This line of code creates a variable named harmOrHealPart. Instead of holding a number, this variable holds script.Parent, a special direction that leads to the part the script is attached to.

In the Explorer, you can see some objects have things attached to them, like the way this script is attached to DangerTrap. Parents are the objects on top, and children are the objects underneath. In this example, DangerTrap is the parent and the script is the child.

By using this code, the game developer doesn’t have to know the exact name of the parent object; this variable will find it no matter what.

Previous Finding the Damage Variable Next Creating More Traps