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!
-- 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.