I cant get the players character

Hey there,

So i am currently making a gun system but i need to call the players character but it isn’t working.

So the current method i’ve tried using is:

local localPlayer = game.Players.LocalPlayer
local char = localPlayer.Character

So that the game gives the character a bit to load, but instead i get this output error:

attempt to index nil with ‘Character’

So i have tried many other things that dont seem to work.
I would appreciate the assistance i can get.

Thank You! :slight_smile:

2 Likes

Is this inside a Local Script?

Hey there! Please try this script;

local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()

If this wasn’t the solution, do let me know. :happy1:

LocalPlayer only works on LocalScripts, and LocalScripts only work when they are client-sided.

this error is happening exactly because of this: you are trying to use localplayer/localscript server-side, not client-side. for more information, read LocalScript (Devhub) and this Players.LocalPlayer(Devhub)

Hello,

I still got the same error.

@davntlvss This is a server script.

@Woesus Is there way to get the players character from the server side?

As I said, LocalScript or LocalPlayer doesn’t work on server-side, or non-localscript, as there’s no way the Roblox engine can detect the local player. and as it does not work, it returns nil

Yes, example:

Players.PlayerAdded:Connect(function(player)
print(player.Name)
end)

1 Like

Oh, I thought it was a local script. Yeah, the local player doesn’t work on the server. But you can do it simply by connecting the event:

local players = game:GetService("Players")
players.PlayerAdded:Connect(function(player)
     local character = player.Character or player.CharacterAdded:Wait()
     print(character) -- Prints the character to make sure that it exists.
end)

This script should be the solution to your issue. Sorry for the misconception as I didn’t know what script you were using. I presumed it was a local script by the .LocalPlayer instance. Very sorry about that. :sweat_smile:

2 Likes