Script not being applied on descendant added

Hey! so im making an script where items spawn randomly around the map, the system is pretty much fully done but the only problem is: The script isnt applying to descendant addeds

Can anyone help me fix that?

The Script

local NotifyModule = require(game.ReplicatedStorage.Modules.Notification)
local Event = game.ReplicatedStorage.Events:WaitForChild("ToolEvent")

function addscript(instance)
	if instance:FindFirstChild("ToolName") then
		print("woah woah")
		instance.GrabPrompt.Triggered:Connect(function()
			local NewString = string.gsub(tostring(instance.ToolName.Value), " ", ""):lower()
			
			instance.GrabPrompt.Sound:Play()
			NotifyModule:Notify(game.Players.LocalPlayer, "Grabbed "..tostring(instance.ToolName.Value))
			Event:FireServer(NewString, instance)
		end)
	end
end

game.Workspace.spawns.DescendantAdded:Connect(function(instance)
	coroutine.wrap(addscript)(instance) -- right here it doesnt apllies the script
end)

for _, v in ipairs(game.Workspace:GetDescendants()) do
	coroutine.wrap(addscript)(v)
	task.wait()
end

Try this script:

--//Services
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

--//Requires
local NotifyModule = require(ReplicatedStorage.Modules.Notification)

--//Variables
local LocalPlayer = Players.LocalPlayer
local Event = ReplicatedStorage.Events:WaitForChild("ToolEvent")

--//Functions
function addscript(instance)
	local ToolName = instance:FindFirstChild("ToolName")
	
	if not ToolName then
		return
	end
	
	instance.GrabPrompt.Triggered:Connect(function()
		instance.GrabPrompt.Sound:Play()
		NotifyModule:Notify(Players.LocalPlayer, "Grabbed ".. tostring(ToolName.Value))
		
		local NewString = string.gsub(tostring(ToolName.Value), " ", ""):lower()
		Event:FireServer(NewString, instance)
	end)
end

workspace.spawns.DescendantAdded:Connect(function(descendant)
	addscript(descendant)
end)

for i, descendant in ipairs(workspace:GetDescendants()) do
	task.defer(function()
		addscript(descendant)
	end)
end

i tried that but it still doesnt works, its kinda weird bc it isnt showing any errors on output

Hm that’s weird. Could you add a print line right before the Triggered function and see if it prints?

Yeah it doesnt prints, i also added a print to after the descendant added just to check and it prints

Do at least some of the descendants have a child called ToolName?

yeah its always the same tool that appears bc i havent added more, but every tool will have ToolName in its children, oh i added a waitforchild and it works now! i will do some tweaking to the wait for child, but thanks for the help i was really really struggling solving this!

1 Like

No problem, if you need anymore help, feel free to ask. Have a great day! (and thanks for solution, i finally have 100!!)

1 Like

Glad i could help you reach that goal! :slight_smile:

1 Like