Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do I make it so a tool spawns only after it was picked up?

Here is a tool spawn script that spawns a tool from a part. It continually spawns a tool every 120 seconds but how do I make it so a tool spawns only after it was picked up then with the spawn time of 120 seconds?

local respawnTime = 120

function spawnWeapon()
    math.randomseed(math.random(1,255))
    local tools = game:GetService("ReplicatedStorage"):WaitForChild("Tools"):GetChildren()
    local toolClone = tools[math.random(1,#tools)]:Clone()
    toolClone.Parent = workspace.Items
    toolClone.CFrame = script.Parent.CFrame + Vector3.new(0,-4,-2)
end

while wait(respawnTime) do
    spawnWeapon()
end

1 answer

✓ Accepted answer

I'd have a table that keeps track of each tool. The original tool is our Key which doesn't change, the value, however, is a table that we can update our data with every time a tool is taken.

https://gyazo.com/8a000197951d6ee1faa6451848be04dc

local ToolsFolder = game:GetService('ReplicatedStorage').Tools
local Tools = ToolsFolder:GetChildren()
local Items = workspace.Items
local RespawnTime = 3


local Cache = {}

local function NewIndex(newTool)
	local self = {}
	
	self.OriginalTool = newTool
	self.ClonedTool = newTool:Clone()
	self.TimeIn = tick()
	self.Taken = false
	
	-- Overwrite original tool so we can update table every time its taken
	Cache[newTool] = self
	self.ClonedTool.Parent = Items
end

Items.ChildRemoved:Connect(function(RemovedTool)
	for _,v in pairs ( Cache ) do 
		-- if tool is our clone then reset time and allow respawn
		if v.ClonedTool == RemovedTool then
			v.TimeIn = tick() 
			v.Taken = true
		end
	end
end)

-- Cache and Spawn tools to map
for _,v in pairs ( Tools ) do 
	NewIndex ( v ) 
end

while true do 
	for _,v in pairs ( Cache ) do 
		-- if Taken and time >= RespawnTime
		if v.Taken and tick() - v.TimeIn >= RespawnTime then 
			NewIndex( v.OriginalTool )
		end
	end
	wait(1)
end

1 comment

0

THX!

This discussion is preserved as it was. New answers, comments, and votes are closed.