How to check if there is already something at certain position?

hello,

so i’m making something were it would spawn random cubes on different positions without placing multiple at the same position.

now…
i don’t exactly know how to do this.
so let’s say you have:

local Position = Vector3.New(0,0,0)

and you spawn a cube on that position like this:

while true do
local Cube = Instance.New("Part")
Cube.Parent = workspace--If statement would begin here 
Cube.Position = Position
Task.Wait(3)--end here
end

Now let’s say you add an if then part in your code that says:

if then --statement not filled because i have to explain this yet
Position = Position + Vector3.New(32,0,0)
Cube.Position = Position
else
Cube.Position = Position
end

How do i check if there is a part already at that position (That’s why the statement is empty)
because if i can check it i can change the position with 32 (On X Axis) and else place a cube there.

Thanks In Advance!

make a table with vector3 values called usedpositions or smth, and check if the random position is equal to any vector3. if it is, then make a repeat loop that changes the position until its not a value in the table. then, add that random vector3 to the table

first off you need to keep track of every spawned cube, I will assume that all cubes spawned will be done by this script, and that no “pre spawned” cubes exist.

local spawnedCubes = {}

local function checkIfOccupied(position: Vector3): Boolean
	for _, cube in pairs(spawnedCubes) do
		if cube.Position == position then return true end -- return true if position is occupied.
	end
end

while true do
	if checkIfOccupied(Position) then
		-- code to run if position is already occupied.
	else
		--code to run if position is not already occupied.
	end
	task.wait(3)
end

I left some empty spaces because I’m confused as to what you want to do exactly, so I left it up to you.

Dont put the cube itself, put its position, since the cube MOVES a few tiny studs while spawning

my bad, I didn’t realize the cube was unanchored.

edited the script:

local spawnedCubePositions = {}

local function checkIfOccupied(position: Vector3): Boolean
	for _, cubePosition in pairs(spawnedCubes) do
		if cubePosition == position then return true end -- return true if position is occupied.
	end
end

while true do
	if checkIfOccupied(Position) then
		-- code to run if position is already occupied.
	else
		--code to run if position is not already occupied.
	end
	task.wait(3)
end

-- IMPORTANT: at cube creation, put it's position into the spawnedCubePositions table
-- table.Insert(spawnedCubePositions, [the position you used])

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