What's a more efficient way to spawn items?

I’m making a game where it spawns random trinket around the map. I’ve created a script that have a 1/5 chance to spawn a random item every 10 seconds, but it requires me to put the script on every spawn location. Is there a more better and efficient way to make this?

Script:

	task.wait(5)
	local chance = math.random(1,5)
	if chance == 1 then
		print("item spawn chance")
		local trinket = math.random(1, 5)
		if trinket == 1 then
			local item = game.ServerStorage.TrinketsClicker.Bracelet:Clone()
			item.Parent = workspace.SpawnedTrinkets
			item.Position = script.Parent.Position
		elseif trinket == 2 then
			local item = game.ServerStorage.TrinketsClicker["Diamond Ring"]:Clone()
			item.Parent = workspace.SpawnedTrinkets
			item.Position = script.Parent.Position
		elseif trinket == 3 then
			local item = game.ServerStorage.TrinketsClicker["Gold Goblet"]:Clone()
			item.Parent = workspace.SpawnedTrinkets
			item.Position = script.Parent.Position
		elseif trinket == 4 then
			local item = game.ServerStorage.TrinketsClicker["Golden Necklace"]:Clone()
			item.Parent = workspace.SpawnedTrinkets
			item.Position = script.Parent.Position
		elseif trinket == 5 then
			local item = game.ServerStorage.TrinketsClicker["Metal Plate"]:Clone()
			item.Parent = workspace.SpawnedTrinkets
			item.Position = script.Parent.Position
		end
	else
		print("didnt spawn")
	end
end	```
1 Like

You should parent after you set all the properties of the instance. In this cause you should set the item position before you parent them.

You can also set all the trinkets within a table and then just use the Chance variable you created to select within the table

Example
local ServerStorage = game:GetService("ServerStorage")
local TrinketsClicker = ServerStorage.TrinketClicker
local Trinkets = { TrinketsClicker.Bracelet, 
TrinketsClicker["Diamond Ring"], 
TrinketsClicker["Gold Goblet"],
TrinketsClicker["Golden Necklace"],
TrinketsClicker["Metal Plate"],
}
task.wait(5)
local chance = math.random(1,5)
local Item = Trinkets[chance]:Clone()
	Item.Position = script.Parent.Position
	Item.Parent = workspace.SpawnedTrinkets

You could create a folder with all the spawn location parts in it then do a for loop that picks a random part that already doesn’t have a trinket spawned on it and spawn one

1 Like