Wait() statement breaks code

Im trying to make a grenade which detonates after a certain period of time, however when i put in the wait statement, it makes the code stop working and the script stop after it

the only thing that fixes it is getting rid of the wait statement, ive tried task.wait but to no avail, i need it as i need a fuse

local Loader = require(game:GetService("ServerStorage"):WaitForChild("ToolPacks"):WaitForChild("WeaponsLoader"))

local ALLOWED_USE_TIME = 0.1
local fuse = 4

local tool = script.Parent

script.Parent.Equipped:Connect(function()
	print("fancy1")
	local clone = game.ReplicatedStorage.Weapons.Grenade:Clone()
	local player = Loader.Players:GetPlayerFromCharacter(tool.Parent)
	local character = player.Character
	local HumanoidRootPart = character.HumanoidRootPart
	local CF = player.Character.HumanoidRootPart.CFrame * CFrame.new(0, 0.5, -4)
	print("22")
	clone.Parent = workspace
	clone.Handle.CFrame = CF
	Loader.RaceRewardsDomainService:AddOrUpdateXpBonus(player)
	print("3")	
		wait(1)
		print("2")
	local Explosion = Instance.new("Explosion")
	Explosion.Parent = workspace
	Explosion.ExplosionType = Enum.ExplosionType.NoCraters
	Explosion.BlastRadius = 3
	Explosion.DestroyJointRadiusPercent = 0
	Explosion.Position = clone.Handle1.Position	
	Loader.DebrisService:AddItem(clone, .1)


		print("3")

		local modelsHit = {}


		

		Explosion.Hit:Connect(function(part, distance)

			local parentModel = part.Parent

			if parentModel then

				if modelsHit[parentModel] then

					return

				end

			

				modelsHit[parentModel] = true


		

				local humanoid = parentModel:FindFirstChild("Humanoid")

				if humanoid then

					local distanceFactor = distance / Explosion.BlastRadius 

					distanceFactor = 10 - distanceFactor 

					humanoid:TakeDamage(120 * distanceFactor) 

				end

			end

		end)


		Explosion.Parent = game.Workspace

	



	end)
local function PurgeTimer()
	wait(ALLOWED_USE_TIME)
	local player = Loader.Players:GetPlayerFromCharacter(tool.Parent)
	Loader.ToolManagerModule:RemoveAllToolsFromPlayer(player)
end
tool.Equipped:Connect(PurgeTimer)
2 Likes

What AddOrUpdateXpBonus does in this event?

Also, please utilise task library as it offers better scheduling system in comparison to the former.

1 Like

it just refers to a module script to run code on there

The issue is happening because of the PurgeTimer() function - It deletes the tool 0.1 seconds after equipping it. This means that the Script that runs this code is also destroyed, hence stopping all operations.

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.