Is repeat wait() bad?

In my code I do repeat wait() until plr.Character but some people say it’s bad but no coding is running it is just repeating wait

And then there is this

I recommend giving the entire topic a read, has useful information, but I just picked out the most relevant quotes for this topic.

1 Like

I understand that but I really just wanna know if i should do that.

It should have been implied that no, you shouldn’t, and instead look into event based programming. 9 times out of 10 there will probably be an event for something.

3 Likes

Your wait is running! Every frame your loop will wake up, check if the character is there yet, and then yield. Exactly when your loop wakes up is unknown, because of reasons @sjr04 outlined.

Here’s an event-based option that yields once (or never) and resumes once:

local player = game.Players.LocalPlayer
local character = player.Character
if not character then
  character = player.CharacterAdded:Wait()
end
1 Like

To get a player character or wait until they load you can do this:

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

CharacterAdded:Wait() will yield the script until the player character loads in and return the character model when it does.

3 Likes

I used that but when I reset for some reason the code breaks.

It’s because the code only runs once and not again every time the character is added.
To make it run every time, use Player.CharacterAdded.

1 Like

So I should do

local plr = game.Players.LocalPlayer
plr.CharacterAdded:Connect(function()
– char is added and this code runs everytime i die
end)

1 Like

Yep this is because when the character dies the character model goes poof and gets destroyed.

To fix this we need to replace the character variable with the new character:

local player = game.Players.LocalPlayer

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

player.CharacterAdded:Connect(function(newCharacter)
	character = newCharacter
end)

So just to be clear a localscript runs everytime the player dies?

Depends on where you put it.

If you put the local script in StarterPlayerScript it will only run once, unless you do something special within the code.

If you put the local script in StarterCharacterScripts the script will run every time the character spawns because the localscript gets copied into the character when the character spawns and hence runs again.

2 Likes