Attempt to index nil when I think everything is good

I’m trying to connect a motor6d to a player when they join.

Local script-

local char = game.Players.LocalPlayer.Character
local M6D = game.ReplicatedStorage:WaitForChild("ConnectM6D")

WeaponTool.Equipped:Connect(function()
	M6D:FireServer(WeaponTool.BodyAttach)
	local ToolGrip = char.UpperTorso:WaitForChild("ToolGrip")
	ToolGrip.Part0 = char.UpperTorso
	ToolGrip.Part1 = WeaponTool.BodyAttach
end)

Server script-

local ConnectM6D = game.ReplicatedStorage:WaitForChild("ConnectM6D")

ConnectM6D.OnServerEvent:Connect(function(plr,location)
	local uppertorso = plr.Character:WaitForChild("UpperTorso")

	local M6D = Instance.new("Motor6D")
	M6D.Parent = uppertorso
	M6D.Name = "ToolGrip"
	M6D.Part0 = uppertorso
	M6D.Part1 = location
end)

However, when I equip the weapon, I get “attempt to index nil with UpperTorso.” , how would I fix this?

It is very possible that the player has not loaded in yet. Change your ServerScript to this:

local ConnectM6D = game.ReplicatedStorage:WaitForChild("ConnectM6D")

ConnectM6D.OnServerEvent:Connect(function(plr,location)
	local character = plr.Character or plr.CharacterAdded:Wait()
	local uppertorso = character:WaitForChild("UpperTorso")

	local M6D = Instance.new("Motor6D")
	M6D.Parent = uppertorso
	M6D.Name = "ToolGrip"
	M6D.Part0 = uppertorso
	M6D.Part1 = location
end)

Same with your LocalScript

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

dang it’s still happening, and I forgot to say it happens in the local script on this line

local ToolGrip = char.UpperTorso:WaitForChild("ToolGrip")

Then move the script to there.

local Players = game:GetService("Players")
local player = Players.LocalPlayer
local M6D = game.ReplicatedStorage:WaitForChild("ConnectM6D")

WeaponTool.Equipped:Connect(function()
	M6D:FireServer(WeaponTool.BodyAttach)
	local char = player.Character or player.CharacterAdded:Wait()
	local upperTorso = char:WaitForChild("UpperTorso")
	local ToolGrip = upperTorso:WaitForChild("ToolGrip")
	ToolGrip.Part0 = upperTorso
	ToolGrip.Part1 = WeaponTool.BodyAttach
end)

You can just define the Character by doing

local char = tool.Parent
if not char:IsA("Model") then
   char = nil
end

Do this after player equipped to tool.

1 Like