I’m using task.defer() in a backpack system I’m working on, In the module script when backspace is pressed this code runs ------>
task.defer(function ()
local slot = self:resolveSlotMapping(self.equippedTool)
self:dropTool(self.equippedTool)
self.guiController:removeTool(slot)
end)
and in a seperate script, this plays ------------->
if inputObject.KeyCode == Constants.KEYBOARD_DROP_ITEM_KEY then
if char and isToolEquipped(char) then
DestroyEvent:FireServer(char.HumanoidRootPart.CFrame)
end
end
When the DestroyEvent is fired, it destroys the tool in your backpack and clones a identical model of the tool with a proximity prompt in it to drop into the workspace.
I want the second script to run first because if it doesnt then the tool isn’t found in the second script.
sorry i was kinda just yapping but i wanted to make sure that thats the correct way to use task.defer() and that the second script will ALWAYS play first, because if you drop a tool and it just disappears forever people would be pretty mad.
Assuming both these code snippets are triggered by the same event, you are using task.defer correctly. This will always guarantee the second snippet runs first.
task.defer only delays execution slightly; it doesn’t synchronize across scripts.
--LocalScript in StarterPlayerScripts
if inputObject.KeyCode == Constants.KEYBOARD_DROP_ITEM_KEY then
if char and isToolEquipped(char) then
DestroyEvent:FireServer(char.HumanoidRootPart.CFrame)
local slot = backpackModule:resolveSlotMapping(backpackModule.equippedTool)
backpackModule:dropTool(backpackModule.equippedTool)
backpackModule.guiController:removeTool(slot)
end
end
This should guarantee the server sees the tool first before it’s removed locally.
(I hope, it’s from my notes, but not in a program I can test with at the moment)
This might work, but it’s on pretty thin ice and I would advise against doing that.
Whenever you need two separate scripts to run in a specific order, you should try to combine them into one script, so the order is both guaranteed and obvious. You can utilize ModuleScripts to convert your code into functions and then have a single script call those functions in the order you need them to run in.