So I was making admin commands and I was making a bring command. To explain it, it just basically teleports the specified player to admin's location.
Now when I made the code, I got this error: Workspace.AdminCommands:15: attempt to index field 'Character' (a nil value)
Here is my code:
local admins = {'FE3_MapTester', 'Player1'} -- Player1 is for experiments game.Players.PlayerAdded:Connect(function(plr) plr.Chatted:Connect(function(msg) for i, admin in pairs(admins) do if plr.Name == admin then -- // Commands if msg:sub(1, 7) == ';bring ' then local target = game.Players:FindFirstChild(msg:sub(8)) if target then local char = target.Character if char then local root = char.HumanoidRootPart if root then local adminRoot = admin.Character.HumanoidRootPart local adminPosX = adminRoot.Position.X local adminPosY = adminRoot.Position.Y local adminPosZ = adminRoot.Position.Z local newPos = CFrame.new(adminPosX - 2, adminPosY, adminPosZ) root.CFrame = newPos end end end end end end end) end)
Error line is 15.
Thanks!
local adminRoot = admin.Character.HumanoidRootPart
admin
is a string, and strings don't have a Character
field. You meant to use plr
. plr is not a good identifier though, I'd suggest player
or client
. Both are immediately clearer than plr
.
Additionally, you can clean up your script. You can use a function that returns true
if a player is an admin. It will return false
if otherwise.
You should also be using the UserId
since players can change their names.
```lua local Players = game:GetService("Players"); --// recommended way of getting all services local adminIds = {123456789, ...}; --// insert the user id's here
local function isAdmin(client) for _, userId in ipairs(adminIds) do if (rawequal(client.UserId, userId)) then return true; --// admin end end return false; --// not admin end
Players.PlayerAdded:Connect(function(client) client.Chatted:Connect(function(msg) if (isAdmin(client)) then --// is admin if (rawequal(msg:sub(1, 7), ";bring ")) then local name = msg:sub(8); local target = Players:FindFirstChild(name) and Players[name]:IsA("Player") and Players[name];
if (target and target.Character) then target.Character:SetPrimaryPartCFrame(CFrame.new(client.Character.PrimaryPart.Position + Vector3.new(0, 0, 5))); --// teleport player end end end end);
end); ```
The rest of the code should be self explanatory. If you would like me to explain some portion do let me know in comments.
I'm guessing the issue is that you're making a reference to the player's character before it's properly loaded. I think you need to do something like
local char = target.Character if not char then char = target.CharacterAdded:wait() end
Let me know if that works.
Edit: Sorry, didn't see that you had fixed it yourself before I posted this.