Random generation of parts

Hello,This is just a quick question. I’m trying to make a generation system like Pet Simulator’s where coins randomly generated fall from the sky. I’m trying to figure out the most efficient way to do this. I’ve tried cloning but i’m not sure how to make an Object generate or be cloned into a random location of a region3 area if you could let me know of a Wiki or something that I can follow to help me figure this out that would be great! Kind Regards TheTimeDefender.

2 Likes

You can use the math.random function for this, couples with a for loop, you can generate x number of parts between positions a and b

for i = 1,69 do
   local p = Instance.new("Part")
   p.Position = Vector3.new(math.random(-120,120),69,math.random(-120,120))
   p.Parent = workspace
end

Making this less specific, you can do something like this:

math.randomseed(tick()) --for more randomness
local p1 = --position 1
local p2 = --position2
local y = --y location for spawn
local numOfParts =--number of parts

for i = 1,numOfParts do
   local p = Instance.new("Part")
   p.Position = Vector3.new(math.random(p1.X,p2.X),y,math.random(p1.Z,p2.Z))
   --p.CFrame = CFrame.new(math.random(p1.X,p2.X),0,math.random(p1.Z,p2.Z)) would also work
   p.Parent = workspace
end
4 Likes

Thank you theking this seems to be working perfectly! Only one question. If I wanted it to be a mesh that had a script in it how would I go about that?

1 Like

So you’re looking for a script that makes coins fall from positions within a Region3?

local coinCount = 50 -- amount of times to drop a coin
local region = Region3.new(Vector3.new(0, 0, 0), Vector3.new(50, 50, 50))
    
-- min and max positions in the X axis
local minPositionX = region.CFrame.X - (region.Size.X/2)
local maxPositionX = region.CFrame.X + (region.Size.X/2)

local minPositionZ = region.CFrame.Z - (region.Size.Z/2)
local maxPositionZ = region.CFrame.Z + (region.Size.Z/2)

local topPosition = region.CFrame.Y + (region.Size.Y/2)

math.randomseed(tick())

for i = 1, coinCount do
	local chosenX = math.random(minPositionX, maxPositionX)
	local chosenZ = math.random(minPositionZ, maxPositionZ)
	
	local coin = game.ServerStorage.coin
	coin.Position = Vector3.new(chosenX, topPosition, chosenZ)
	coin.Parent = workspace
	
	wait()
end
3 Likes

You could, instead of instancing a new part, you could clone said model from wherever it is (im using serverstorage as an example)

local mesh = game.ServerStorage.Mesh
for i = 1,numOfParts do
   local p = mesh:Clone()
   p.Position = Vector3.new(math.random(p1.X,p2.X),y,math.random(p1.Z,p2.Z))
   p.Parent = workspace
end
3 Likes

Both of these worked! Thanks again guys. I really do appreciate it. I really like how helpful the roblox community is!

6 Likes