PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience

Removing Parts From a Character

Removing Parts From a Character

Jun 29 2018, 4:51 PM PST

Problem

You want to remove all the parts of a character.

Solution

You use the GetChildren method and check if the objects are parts.

local pl = Workspace:FindFirstChild("Player")
if pl then
	for _, v in ipairs(pl:GetChildren()) do
		if v:IsA('BasePart') then
			v:Destroy()
		end
	end
end

Discussion

The first two lines do the standard safe indexing of the character. The interesting part starts on the third line. We do the general for loop, but instead of inputting a table to the iterator function, we input the result of the GetChildren method on the character (which happens to return a table).

As you have probably noticed all the objects are in a hierarchical structure. At the top of this hierarchy is game. The next level is Workspace (in later recipes we will get into different directories than just the workspace) which is where all rendered parts go. Inside the workspace are all types of different objects, parts, models (which just serve as containers for other objects), etc. As it turns out Workspace.Player is actually a model (since all objects related to that specific player’s character are put in there).

By doing Workspace.Player:GetChildren() we are getting all the objects inside of that player model. This includes the limbs, humanoids, and various other types of objects relating to the character. Then we can put the result of that function into an iterator function (since it returns a table with all these objects), and we can iterate over them.

Now, we cannot just do v:Destroy() because the goal of this was to remove all the parts of the character, we want to save the Humanoid object and the other objects. Therefore, we must check to see if the object we are iterating over is in fact a Part. In order to do this we use the IsA method. It returns true or false based on whether the object is the specified type. This is then put into a conditional and if the object is a part, then it’s removed.

We can also do something like if v.ClassName == 'Part' then. The ClassName property is the type of object the object is. We can see if that is equal to part and get the same result. Do note however there is a subtle difference between x.ClassName == 'y' and x:IsA('y').

Tags:
  • loops
  • humanoid
  • coding