Problem with finding character

Im developing a game and i needed to be able to control the spawn of a player, so i disable the characterautoload and added a script to the sss:

local Players = game:GetService("Players")

Players.CharacterAutoLoads = false

local function onPlayerAdded(player)
	local function onCharacterAdded(character)
		local humanoid = character:WaitForChild("Humanoid")
	end
	player.CharacterAdded:Connect(onCharacterAdded)

	player:LoadCharacter()
end

Players.PlayerAdded:Connect(onPlayerAdded)

everything works, except this script:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local weaponModule = require(ReplicatedStorage.Modules.WeaponModule)

game.Players.PlayerAdded:Connect(function(player)
	print("Player Found")
	player.CharacterAdded:Connect(function(character)
		print("Character Found")
		character.ChildAdded:Connect(function(child)
			if child:IsA("Tool") and child:FindFirstChild("Shoot") then
				local tool = child

				local shootEvent = tool:WaitForChild("Shoot")
				if shootEvent then
					print("event found")
				end
				shootEvent.OnServerEvent:Connect(function(player, mousePosition)
					print("shot event from server fired")
					weaponModule.Shoot(player, tool, mousePosition)
				end)
			end
		end)
	end)
end)

it stops at the player found print, so my guess is that there’s something wrong with the character load. The thing is that the script works sometime, and some time not, so my other guess it has to do with the loading order?

Idk how to fix this, pls help me.

I’m not sure, but I believe this is because you are waiting for the character Before loading it, meaning it doesn’t exist.
tell me if i’m wrong

Maybe the character is already loaded in when player.CharacterAdded runs, as the CharacterAdded event only activates when the character loads in; not if the character is already loaded.

Ok, yeah, i replaced the CharacterAdded, and it actually found the character. So yeah it was waiting for a character add when character was already added.

You should practice safer patterns.

local function onPlayerAdded(player)
    print(player.Name, "joined the game")

    local function onCharacterAdded(character)
        print(character.Name, "spawned")
    end

    -- connect CharacterAdded signal
    player.CharacterAdded:Connect(onCharacterAdded)

    -- manually fire if the character already exists
    -- before the CharacterAdded signal gets connected
    if player.Character ~= nil then
        task.spawn(onCharacterAdded, player.Character)
    end
end

-- connect PlayerAdded signal
Players.PlayerAdded:Connect(onPlayerAdded)

-- manually fire for any players that may already be in game
-- before the PlayerAdded signal gets connected
for _, player in Players:GetPlayers() do
    task.spawn(onPlayerAdded, player)
end

Alright, glad to be of help :slight_smile:

(also feel free to mark my message as a solution lol, this is my first ever)

1 Like