Function Variable Coming back as nil

Hey, recently I’ve been working with this code. Its designed so it runs through all the players in the game, and then creates a “Died” function for them. this issue is when this variable is printed, its coming out as nil. does anyone know why this is? I feel like I’m missing something really simple and made a dumb mistake.

for _, player in pairs(game.Players:GetChildren()) do
		player.character.Humanoid.Died:Connect(function(char)
		print(char)
	end)
end

I don’t think Humanoid.Died returns any variables, so you can probably just put player.Character instead of trying to get it from the event.

2 Likes
local Players = game:GetService("Players");

for _, Player in Players:GetPlayers() do
    local Character = Player.Character; if not Character then continue end;
    local Humanoid = Character:WaitForChild("Humanoid", .1); if not Humanoid then continue end;

    Humanoid.Died:Connect(function()
        print(Character); -- use it here smh
        print(Player.Name .. " died!");
    end);
end

if you want this code to be in a different context then just tell me

this code’s functionality can be improved dependent on ur situation

like if u want to want until the character exists and not just skip it you can change to

local Character = Player.Character or Player.CharacterAdded:Wait()

if you want to only run the Humanoid.Died function once then just do this instead

    Humanoid.Died:Once(function()
        print(Character); -- use it here smh
        print(Player.Name .. " died!");
    end);
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.