Feedback on my star creation script

This is the code I used for my space game. I’m trying to create a star generation system.

  • How could I make it better?

Here’s my script in ServerScriptService:

local starcount = 0
local maxc = 200

while wait() do
	local b = Instance.new("Part")
	b.BrickColor = BrickColor.new("White")
	b.Parent = workspace
	b.Shape = Enum.PartType.Ball
	b.Position = Vector3.new(math.random(0,200), math.random(0,200), math.random(0,200))
	b.Size = Vector3.new(0.9,0.9,0.9)
	b.Anchored = true
	starcount = starcount + 1
	print(starcount)
	if starcount == maxc then
		print("Max") 
		break
	end
end

Thank you for any help!

1 Like

First off, you shouldn’t really be using a while wait() do loop, its bad practice. What would be great for this situation is a for loop, since you’re only doing it for a certain amount of iterations anyways.

5 Likes

I’m not very new to scripting but do you mean this:

for i = 0, 200 do
	local b = Instance.new("Part", workspace)
	b.BrickColor = BrickColor.new("White")
	b.Shape = Enum.PartType.Ball
	b.Position = Vector3.new(math.random(1,100),math.random(1,100),math.random(1,100))
	b.Size = Vector3.new(0.9,0.9,0.9)
	b.Anchored = true
	i = i + 1
	if i == 200 then
		break
	end
end

You got the for loop right, but you can remove this part because that’s the functionality of a for loop.

i = i + 1
if i == 200 then
   break
end

Sorry for the bump, but I’d also add a magnitude check for any existing stars.

Ensuring you check the magnitude and only insert the star if there’s sufficient space between Star1 and Star2 means you won’t have any colliding.

1 Like