Are you able to have parts spawn in random places with Instance.new?

I am trying to get parts to spawn in random places but I’m not sure if that’s possible. When I tested my script it was all spawning from the same place.

local RandomNumber = math.random(1,5000)
local RandomNumber2 = math.random(1,5000)

while true do
	local new = Instance.new("Part")
	new.Parent = game.Workspace
	new.Position = Vector3.new(RandomNumber, 200, RandomNumber2)
	new.BrickColor = BrickColor.new("Cyan")
	new.Name = "Thing"
	wait()	
end

Assuming that the code you provided in the original post is everything in that script, the RandomNumber variables are initialized as soon as the script starts running and are never assigned a new value.


If you include the RandomNumber variables within the loop, it’ll generate new values every iteration.

Example:

while true do
    local RandomNumber = math.random(1,5000)
    local RandomNumber2 = math.random(1,5000)

	local new = Instance.new("Part")
	new.Parent = game.Workspace
	new.Position = Vector3.new(RandomNumber, 200, RandomNumber2)

    -- Continue
1 Like

Put the Random variables inside while loop

Wow, I can’t believe I missed that, thanks for the help!

1 Like

This is an obvious question to an obvious answer. Also you need to generate the number within the loop. ALSO adding into @renealbert12345’s answer, you should use a RandomObject, which is created as Random.new().

local RANDOM = Random.new()

while true do
    local randomX = RANDOM:NextNumber(...)
    local randomZ = RANDOM:NextNumber(...)
end