I need to know this for a drowning/air script, and I can't figure out how to reference it.
Don't get too aHEAD of yourselves! You still need the character! Get it?
If we dive into the Player object
We can see that the Player
has a property that we might like.
The Character
property of Player
returns the model that we control whenever we're playing.
What's also awesome about this property? It's not Read - Only
, so we can change it!
But we're getting off - topic, and I'm a professional scripter, I don't go to OT(or do I?)
Character
objects also have a child, named Head
, which is the head we're looking for!
BAM IM AMAZING AT ANSWERING.
game.Players.PlayerAdded:connect(function(plr) print(plr.Character.Head.Name) end)
BAM
Uh oh, errors!
Why is this erroring?
We are trying to access the Character
of the Player
while it might not be loaded yet! Scripts load the fastest in Servers, which is a bad thing if you're not waiting for anything because it'll cause everything to error.
How do we wait for the Character
:WaitForChild("Character")
?
No, for one, the Character is not a Child
of Player
, but rather, a property.
How then?
There's an event for the Player
named CharacterAdded
, which fires whenever the Character
of a Player
spawns!
So we can use that in out scripts!
game.Players.PlayerAdded:connect(function(plr) plr.CharacterAdded:connect(function(char) local head = char:WaitForChild("Head") --Just incase Head hasn't loaded yet. end) end)
Yes, I totally thought this up myself
The Touched
event returns a Part
Part.Touched:connect(function(hit) --Hit is the part that touched out 'Part' end)
If a character touches it? It simply returns a part of the character, not the character itself. So, since it's a child of Character, we can so script.Parent!
part.Touched:connect(function(hit) if hit.Parent:FindFirstChild("Humanoid") then local head = hit.Parent:WaitForChild("Head") end end)
If you have a character
, the head is just going to be character.Head
, since the head of a player is named "Head".
If you're handling this from a LocalScript, you can get the local Character like this:
local player = game.Players.LocalPlayer local character = player.Character or player.CharacterAdded:wait() local head = character.Head -- do whatever to `head`
If you're handling this from a Server Script, you can get each new character like this:
function newPlayer(player) player.CharacterAdded:connect(function(character) local head = character.Head -- do whatever to `head` end) end game.Players.PlayerAdded:connect(newPlayer) for _, player in pairs(game.Players:GetPlayers()) do newPlayer(player) end