Wierd Instance:IsDescendantOf() Behavior on The Client

Hi folks! Today I have something to show and would like to ask why exactly it happens. I’ll demonstrate.

So we have this small script

for _,v in pairs(game.Workspace:GetDescendants()) do
	if v:IsA('BasePart') then
		local isplr = false
		for _,p in pairs(game.Players:GetPlayers()) do
			if v:IsDescendantOf(p.Character) then
				isplr = true
			end
		end
		if not isplr then
			print('"' ..v.Name ..'" is not in a player character')
		end
	end
end

the code is self explanatory, go through all BaseParts in workspace and tell me if they’re not a descendant of a player’s character. now we put this in ServerScriptService and see if it works…

aaand it works as expected, but here’s the part that bothers me, if we now turn this into a localscript and put it in StarterPlayerScripts and uhhh

and nothing, if you change the code in this manor:

for _,v in pairs(game.Workspace:GetDescendants()) do
	if v:IsA('BasePart') then
		local isplr = false
		for _,p in pairs(game.Players:GetPlayers()) do
			if v:IsDescendantOf(p.Character) then
				isplr = true
			end
		end
		if isplr then
			print('"' ..v.Name ..'" is in a player character')
		end
	end
end

then uhhhhhhh

now it says that EVERYTHING is a descendant of a player character. The solution to fix this is to either put the code in StarterCharacterScripts or to add the following before the block of code

game.Players.LocalPlayer.CharacterAdded:Wait()

This works fine for what i want to do in my case, but I’d like to know why this exactly happens or if this is intentional or not.

That’s all, have a nice day :wave:

Not sure if I’m mistaken but it might be buggy because it’s a new feature. FindFiratDescendant for example is disabled via FFlag because it is in beta.

While weird there is an explanation. Before your player’s character spawns the Player.Character attribute will be nil. Since the DataModel (game) has a parent of nil, if you pass nil as an argument to Instance.IsDescendantOf() you get true. The logic being that your parts are descendant of game which is a descendant of nil. So another way to “fix” your code would be to make sure p.Character is not nil.

From Instance.IsDescendantOf()

Note, DataModel is a descendant of nil. This means IsDescendantOf cannot be used with a parameter of nil to check if an object has been removed.

2 Likes

Oh ok now that makes sense, thanks for the explanation!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.