Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How do I find a specific part inside of workspace through its position?

I have a script that sets a value inside of ReplicatedStorage to a position of a part. I would like to delete this part through its position, as I have a model with more than 100 parts using the same name. Any suggestions?

3 comments

0

loop through workspace and check if its position = the position you want

0

Its inside of a model, and that adds a small delay.

0

Also, how am I supposed to loop through it?

1 answer

An array is a list of index-value pairs in numerical ascending order. It looks like this:

local array = {[1] = "Example", [2] = "Another example"}

Or this:

local array = {"Example", "Another example"} -- same thing as previous line of code

We use this function called ipairs or pairs to iterate/loop through tables like an array. ipairs being made specifically for arrays. We combine this with the for do phrase to do the iteration.

Then we have our function that every Instance automatically has called :GetChildren() which returns a list or array of its children. :GetDescendants() is another option if you must check inside everything in case the part can be inside a Model.

Because there is literally no function that can tell you an object based on position because it sounds very unnecessary, you should ideally find a different way like maybe a table of your possible objects. However, I'll still tell you how to do this continuing below.

We will use a function also automatically part of Instances called :IsA() which returns a boolean (true/false) if it is the specified class name or inherited class name you give it. In our case, we want to check every single part so BasePart is the relevant class name to use as it encompasses all unions, mesh parts, and normal parts as well.

Here is our end result:

local function findPart(vector3) -- give it a Vector3 and not a CFrame value
	for index, object in ipairs(workspace:GetChildren()) do -- index is useless and could be replaced with _
		if object:IsA("BasePart") then
			if object.Position == vector3 then -- compare Vector3 values to be equal
				return object -- give back the object itself
			end
		end
	end
end

Notice: If there are multiple objects with the same position that you're looking for, you will still receive one object. A solution is to create an empty table and add objects in which their positions matches the given Vector3 argument then pass it back as a return value.

This discussion is preserved as it was. New answers, comments, and votes are closed.