How do i protect my game from glitching when a player leaves

Certain codes use the player and it’s character to work. a scenorio can happen. when the player leaves. just before the code executes. and it will glitch because there is no player.

I thought about use if statements. “if player. Character ~= nil” but there is so much code in my game. and i could put an if statement like on almost every piece of code. but that will be a very tedious and time consuming method. do you have any other ways. i can make sure that when a player leaves. a piece of code that uses the player or character. wont glitch and break the game

you should do this:

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

This gets the character if it loaded and if it didn’t, it’ll wait for it to load

also

Have you used Players.PlayerRemoving?

1 Like

I used to have similar problems with older games of mine, and there are two very easy ways to work around this.

1 - Wrap your code in pcall(). This will allow you to handle the errors from the script itself, and it won’t break the current thread being executed.

2 - Your second option is to just create a new thread (using spawn() or firing a BindableEvent). I much prefer and reccommend pcall() for what you are trying to do, but this can also work.

1 Like

I’ll check that out. do you have a link for pcall on the devhub. i cant find it on there

2 Likes