UevKF8zjRV_WEtpJsXhr
We use cookies on this site to enhance your user experience

WaitForChild() Helps Avoid Run-time Errors

Because scripts in Roblox run at different times, it’s possible that a player’s head might not be created yet. To avoid errors, like trying to find a part that doesn’t exist, the script uses WaitForChild() to get the head part attached to the player’s character instead of using the dot operator, like player.Head.


  1. Add a wait function and destroy the particles after one second.
local particle = Instance.new("ParticleEmitter")
particle.Color = ColorSequence.new(currentColor)

local playerCharacter = player.Character
particle.Parent = playerCharacter:WaitForChild("Head")

wait(1)
particle:Destroy()
  1. Playtest the game and make sure particles briefly follow the player after touching each color.
Troubleshooting Tips
  • Make when creating a new instance that ParticleEmitter is spelled exactly as shown and inside quotations.
  • When parenting the particles, make sure to use : between playerCharacter and WaitForChild() with no spaces between.

Finished Project Sample

Project File

Download the finished project here.

Finished Script

local pointPart = script.Parent
--local storage = game:GetService("ServerStorage")

-- Gives some points
local blue = Color3.fromRGB(0, 0, 255)
-- Gives more points
local green = Color3.fromRGB(0, 255, 0)
-- Makes players lose points
local red = Color3.fromRGB(255 ,0, 0)

-- gold given to players
local smallPoints = 10
local largePoints = 50
local losePoints = 100

local Players = game:GetService("Players")

local function givePoints(player)
	local currentColor = pointPart.Color

    local playerStats = player:WaitForChild("leaderstats")
	local playerPoints = playerStats:WaitForChild("Points")

	-- Gives player gold based on the color of the part
	if currentColor == blue then
	    playerPoints.Value = playerPoints.Value + smallPoints	
	elseif currentColor == green then
	    playerPoints.Value = playerPoints.Value + largePoints
	else
	    playerPoints.Value = playerPoints.Value - losePoints	
	end

	-- Destroy the part, wait a second, and thne destroy the particle
	pointPart:Destroy()
	
	-- Creates a sparkles effect and destroys it
	local playerCharacter = player.Character
	local particle = Instance.new("ParticleEmitter")
	particle.Color = ColorSequence.new(currentColor)
	particle.Parent = playerCharacter:WaitForChild("Head")
	wait(1)
	particle:Destroy()

end


local function partTouched(otherPart)
	--local player = Players:GetPlayerFromCharacter(otherPart.Parent)
	local player = game.Players:GetPlayerFromCharacter(otherPart.Parent)

	if player then
		givePoints(player)
	end
end

pointPart.Touched:Connect(partTouched)

-- Changes the color of the part based on variables. Needs to be at bottom of script. 
while true do
	pointPart.Color = blue
	wait(4)
	pointPart.Color = green
	wait(3)
	pointPart.Color = red
	wait(2)
end