hello all, I have this script and its a server script, for some reason on like 5 where i define char, it tells me attempt to index nil with child. what exactly is wrong here?
Players.PlayerAdded:Connect(function(player)
local currentStamina = Instance.new("IntValue")
currentStamina.Name = "currentStamina"
currentStamina.Value = 100
currentStamina.Parent = player
local char = player.Character:WaitForChild("Humanoid")
char.Jump.Changed:Connect(function()
if char.Jump then
print("player jumped!")
staminaTimer = 5
end
end)
end)
Sometimes the player’s Character may not load when the player enters the game, you can use CharacterAdded:Wait() to wait and get the model at the same time.
Players.PlayerAdded:Connect(function(player:Player)
local currentStamina = Instance.new("IntValue")
currentStamina.Name = "currentStamina"
currentStamina.Value = 100
currentStamina.Parent = player
local Character = (player.Character or player.CharacterAdded:Wait())
local char = Character:WaitForChild("Humanoid")
char.Jump.Changed:Connect(function()
if char.Jump then
print("player jumped!")
staminaTimer = 5
end
end)
end)
ok so that worked, but could you explain to me charactedadded? I’ve been having a ton of issues with it working/not working, server scripts or local scripts both it’s all just a mess to me
Sure, CharacterAdded is an RBXScriptSignal that, when using Connect or Wait, returns the player’s Character, this signal is triggered every time the player loads his Character.
This means that, if Character does not exist, it will wait for CharacterAdded to return one, this is a way to make sure Character exists, since it is a property and can sometimes give nil.