I have a problem, my script is using the “CharacterAdded” however sometimes it works and sometimes it doesn’t and my whole game stops working. I would appreciate your help.
game.Players.PlayerAdded:Connect(function(Player)
local Stats_Folder = Player:WaitForChild("Stats")
local Biceps_Value = Stats_Folder:WaitForChild("Biceps")
local Torso_Value = Stats_Folder:WaitForChild("Torso")
local Forearm_Value = Stats_Folder:WaitForChild("Forearm")
local Legs_Value = Stats_Folder:WaitForChild("Legs")
local GamePasses_Folder = Player:WaitForChild("GamePasses")
local SteroidsPass = GamePasses_Folder:WaitForChild("Steroids")
---the script freezes here
Player.CharacterAdded:Connect(function(Character)
local NewValueforMax = 50000
if SteroidsPass.Value == true then
NewValueforMax = 100000
end
repeat wait() until Character:FindFirstChild("Humanoid") and Character:FindFirstChild("LeftUpperArm") -- triying to fix
task.wait(0.5)
First, check if the player’s character already exists. You can handle it immediately without relying on the event.
if Player.Character then
-- Handle the existing character here
end
Instead of using a repeat loop with wait(), you can use a while loop and yield the thread with wait() inside it.
while not (Character:FindFirstChild("Humanoid") and Character:FindFirstChild("LeftUpperArm")) do
wait()
end
It’s possible that the CharacterAdded event is firing after the player has left the game. You can check if the player is still in the game by using the Parent property of the player’s character.
Player.CharacterAdded:Connect(function(Character)
-- Check if the player is still in the game
if Player.Character.Parent ~= workspace then
return
end
-- Rest of your code
end)
Try replacing the connection at line 19 with a repeat until loop. So it should look like this.
repeat wait() until Player.Character ~= nil
local NewValueforMax = 50000
if SteroidsPass.Value == true then
NewValueforMax = 100000
end
repeat wait() until Character:FindFirstChild("Humanoid") and Character:FindFirstChild("LeftUpperArm") -- triying to fix
task.wait(0.5)
--Whatever you want to do after this.
No. Replace the connection at line 19. Sorry, I accidentally said line 22 earlier. You can get rid of line 22 after that. Again, it should look like this:
--Whatever comes before this.
print("Solo llego aqui")
repeat wait() until Player.Character ~= nil --Line 19
print("Solo llego aqui eeeeeee")
local NewValueforMax = 170000
--Whatever comes after this.
The issue lies in your yielding statements in getting the values needed. Because the code is yielding for these values, there is a possibility that the character has already spawned in, so CharacterAdded won’t fire. To get around this just add this statement that checks if the player’s character already exists.
game:GetService("Players").PlayerAdded:Connect(function(Player)
-- your code
if (Player.Character) then
YourCharacterAddedFunction(Player.Character)
end
Player.CharacterAdded:Connect(YourCharacterAddedFunction)
end)