Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What is the best way to wait for characters?

I really want my game to not lag, I want to reduce as much lag as I can, so I was wondering if this is a good way to wait for the Character in LocalScripts

local Player = game.Players.LocalPlayer
local Character = nil

Player.CharacterAdded:connect(function()
	wait()
	Character = Player.Character
end)

repeat wait()
until Character ~= nil

1 answer

✓ Accepted answer

Older scripts will use a repeat wait loop but now we have a very reliable way to wait for an event using the RBXScriptSignal Wait. note that a RBXScriptSignal should not be confused with a RBXScriptConnection which is an object passed back when using :Connect.

The standard method of waiting for the players character is to use:-

local plr = game:GetService('Players').LocalPlayer

local char = plr.Character or plr.CharacterAdded:Wait()

To understand how this code works we first need to know how or works. Or returns its second argument if the first is nil/false. So we first try to access the players character which if found will not be nil so no wait is needed.

If the character is not found then we run the second piece of code which will wait until the event CharacterAdded is fired and pass back any arguments in this case the character which is what we need.

This method saves both time and is more robust that just waiting in an infinite loop.

Lastly it is good to note that putting a local script in the StarterCharacterScripts folder will run each time the player spawns and since its parent is the character there is no need to use any form of checking as, local char = script.Parent will always be the character.

I hope this helps.

1 comment

0

Thanks, I was looking for a solid answer as well :D

This discussion is preserved as it was. New answers, comments, and votes are closed.