Check if a selected part is the child of a player's character

I am working on a pick up parts system, and the bug of being able to pick up players kind of became a feature, as it was really popular with my testers. For the system to run smoothly, any parts that are picked up have their network ownership set to the player picking them up, and back to the server after it is set down. However, this isn’t great for picking up players as their network ownership is set to the server and is laggy. I tried to fix it by using an if statement to check if the parent of the part had a humanoid within it, but it broke the script and wouldn’t assign any actual parts to the server. It just returned this error:


I’m hoping someone with more expertise can help.

script:

`local rep = game:GetService("ReplicatedStorage")

rep.Events.OwnershipEvent.OnServerEvent:Connect(function(player, part, action)
	if action == "Add" then
		part:SetNetworkOwner(player)
		
	elseif action == "Remove" then
		if part.Parent:WaitForChild("Humanoid") then
			local players = game:GetService("Players")
			local Pickedplayer = players:GetPlayerFromCharacter(part.Parent)
			part:SetNetworkOwner(Pickedplayer)
			
		else
			part:SetNetworkOwner(nil)
		end
	end
end)`

Your immediate issue is you should use :FindFirstChild() so it immediately returns nil if there’s no humanoid.
I believe you can use this to determine if a parts’ parent is the character, though I’ve not tested:

if part:FindFirstAncestorOfClass("Model") == char then--let char be the reference to the players' Character
	--
end
2 Likes
if part:IsDescendantOf(player.Character) then
	--Do code.
end
3 Likes

Can’t you just put BoolValue Inside the part Instead of Humanoid?

Btw, @MP3Face is right, you should use :FindFirstChild() instead, so it will return nothing if there’s no Instance that script trying to find.