A problem in a script

Hello Developer Forum users, its that person again, Dev

Please read ALL of this post before replying, I got into issues with my last one because people didn’t really read all of it :confused:
I’m not really in a happy state right now, it’s a personal problem.

I’ve been having issues with my script:

local player = game.Players.LocalPlayer
local char = player.CharacterAdded:Wait() or player.Character
local HRP = char:WaitForChild("HumanoidRootPart")
local mDist = 30

function getTarget()
for _, Parts in pairs(workspace:GetChildren())do
	local Hm = Parts:FindFirstChild("Humanoid")
	local tso = Parts:FindFirstChild("Torso")
	local uptso = Parts:FindFirstChild("UpperTorso")
	
	if tso or uptso then
		if tso or uptso ~= HRP then
		    if (tso.Position - HRP.Position).Magnitude or (uptso.Position - HRP.Position).Magnitude < mDist then
		        print("Hi")
	        end
	    end
	end
end
end

while wait(1) do
	getTarget()
end

Tried HRP (HumanoidRootPart), got the same problem
I keep getting this error:

  Players.TheUnderratedDev.PlayerScripts.GH:14: attempt to index nil with 'Position'

I did this same thing with a raycast tutorial I saw with TheDevKing I looked at 1 or 2 months ago, it worked, I’m not sure if Roblox made a change with this.

This might be a simple mistake. If it is I’m sorry I wasted your time.

Hopefully, I can receive help with this
Thanks, Dev

I think you forgot to add .Magnitude right here.

Thanks, fixed it but still doesnt work

Do you have any errors in the output?

yep, the same error

30 characters

I don’t seem to be finding anything wrong. Maybe instead of this try doing :WaitForChild()

Maybe the parts haven’t properly loaded in?

There are no errors but it doesn’t fire the print function, I’ll see if I can do some more checks.

The problem is that your script is always running even if the Parts is don’t have Humanoid it it. You should check first if Humanoid exists

		local Hm = Parts:FindFirstChild("Humanoid")
		if Hm then -- check this first so that if Parts don't have Humanoid its not continue
			local tso = Parts:FindFirstChild("Torso")
			local uptso = Parts:FindFirstChild("UpperTorso")
			-- continue
		end

Also you should not do if tso or uptso ~= HRP altogether because the same reason, even if one of those 2 not exists your code still running. Split them into 2 different blocks like this,


			if tso and tso ~= HRP then
				 if (tso.Position - HRP.Position).Magnitude < mDist then
					print("Hi")
				end
			end
			if uptso and uptso ~= HRP then
				if (uptso.Position - HRP.Position).Magnitude < mDist then
					print("Hi")
				end
			end

Hope this solve your problem.

I see now, I tested the script with this and another way which came from this method and worked, Thanks a lot

1 Like