How to reference Character correctly?

How do you reference the Character object correctly?
I understand that this topic probably exists already, but most of them have aged well and the content there may be deprecated. Perhaps it would be best for everyone to repeat this topic, both for new and experienced scripters alike. tell me if you have any issue with this post though.

I know that one can simply use player.Character and player:WaitForChild("Character"), but unfortunately, Studio either returns “nah” or an infinite yield on “Character”. So, I was wondering what do you use to get the character model and the like (humanoid, etc.)? Is there another way to do it except the above?
Thank you! :slight_smile:

do player.CharacterAdded:Wait() (it will return the character once that function has been called)

but it is used after an or statement, before that player.Character is defined first

local character = player.Character or player.CharacterAdded:Wait()
2 Likes

If the script loads and runs before the character instance is created, this will result in “nil”, because there is nothing yet.

This will yield because the :WaitForChild() will only search for instances that are a child of Player, which Character is not.


Instead add this part before your functions to make sure it waits until setting the instance;

local Players = game:GetService("Players")

local player = Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
1 Like
-- Referencing Character

local plr = game.Players.LocalPlayer

local char = plr.Character or plr.CharacterAdded:Wait()

-- Assuming you want to use it to transfer over client to server

local event = game.ReplicatedStorage.Event -- Directory. E.g: ReplicatedStorage

-- Lets say you want it to fire when F is clicked:

local uis = game:GetService("UserInputService")

uis.InputBegan:Connect(function(examplekey) -- examplekey being the input
    if examplekey.KeyCode == Enum.KeyCode.F then
        local value = char.Name
        event:FireServer(value) -- whatever data you want to transfer to server: E.g: Value
end)

Server Side Script (ServerScriptService or Workspace)

game.ReplicatedStorage.Event.OnServerEvent:Connect(function(plr, value) -- the first "plr" is always going to be the local player, even if its named "eee". The second and onwards are variables that are transfered from the local script.
    print("transferred data, "..value) -- prints the character's name
end)

If you want more information on character referencing then feel free to ask. Im just trying to help out here, and I don’t know your full extend on scripting, hence why I created this that may help or others that may visit this post in future.

1 Like

Thank you so much for your help!! Now I know how to do it)))))

1 Like

No problem! Feel free to mention me in future topics

1 Like

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