Roblox Beginner Scripting Tutorial - Episode on Functions
Instructor: Balev
Topic: FindFirstChild
and WaitForChild
functions in Roblox
Overview
- Purpose: Learn to locate objects in Roblox and understand game structure.
- Game Structure:
- Games are composed of different folders and objects.
- Parent-Child Relationship:
- The Workspace is a parent to all visible parts in the 3D world.
- Each object, like a base plate or a texture, has a specific parent-child relationship.
Organizing Objects in Roblox
- Two main ways to organize objects:
- Models: Groups parts together as a single unit.
- Example: Creating a model with parts named "Part1", "Part2", "Part3".
- Folders: General organization for parts, scripts, and other assets.
- Allows dragging individual parts or the whole folder.
- Recommendation: Use models for grouping parts; use folders for general organization.
FindFirstChild
Function
- Purpose: Safely locate an object without causing errors if the object doesn't exist.
- Example Usage:
- Syntax:
local part1 = model:FindFirstChild("Part1")
- If part1 exists, actions can be executed (e.g., changing its color).
- If it doesn't exist, no error is thrown, and the script continues.
Implementation Example
- Insert a Script in Model.
- Locate the Model:
- Use
script.Parent
to reference the model directly.
- Locate Part Using
FindFirstChild
:
- Syntax:
local part1 = model:FindFirstChild("Part1")
- Color Check Example:
- If
part1
exists, change its color.
if part1 then part1.BrickColor = BrickColor.new("Cocoa") end
WaitForChild
Function
- Purpose: Wait for an object to be added to the game for a specific period before continuing execution.
- Allows the script to handle situations where an object may not be immediately available.
Implementation Example
- Use:
local part2 = model:WaitForChild("Part2")
- Print Confirmation:
print("Part two has been detected")
- Handle Delays:
- If
part2
is missing, the script waits and checks for it.
Practical Example: Creating a Kill Brick
- Objective: Create a part that kills the player when touched.
- Steps to Create:
- Insert a Part: Name it "Kill Brick" and assign it a red color.
- Insert Script into the Kill Brick.
- Find Kill Brick Reference:
local killBrick = script.Parent
- Handle Player Touch Event:
killBrick.Touched:Connect(function(otherPart) ...
- Find Humanoid: Identify if the touched part is part of a player character.
- Use
local humanoid = otherPart.Parent:FindFirstChild("Humanoid")
- Set Health to Zero:
if humanoid then humanoid.Health = 0 end
- Testing: Test the game to see if touching the brick resets the character.
Conclusion
- Learning Goals: Experiment further with
FindFirstChild
and WaitForChild
.
- Encourage sharing code snippets in comments for community learning.
Next Episode: Stay tuned for more scripting tutorials!
Take Care!