How to give players one random tool from there datastore

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

i want players to be given one random tool they own from a datastore when they join the game

  1. What is the issue? Include screenshots / videos if possible!

i dont know how to give them one random tool that they own from there datastore

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

i been looking on the developer hub and on youtube but did not find any way to fix it

thats the code i got so far

local datastoreService = game:GetService("DataStoreService")
local myDataStore = datastoreService:GetDataStore("SAVED_TOOLS") 

local NightTools = game:GetService("ServerStorage"):WaitForChild("NightTools")

function giveRandomTool(player)
	local success, data = pcall(function() return myDataStore:GetAsync(player.UserId) end) 
	if success then
		-- Player has existing data
		if data.Tools then
			-- Player already has tools, do nothing
			return
		end
	end

	-- Get a random tool from ServerStorage
	local allTools = NightTools:GetChildren()
	local randomIndex = math.random(1, #allTools)
	local randomTool = allTools[randomIndex]:Clone()

	-- Equip the tool to the player
	player.Character:WaitForChild("Humanoid").EquipTool(randomTool)

	-- Update the datastore (if necessary)
	if success then
		data.Tools = {randomTool.Name} -- Store the given tool name
		pcall(function() myDataStore:UpdateAsync(player.UserId, data) end) 
	else
		local data = {Tools = {randomTool.Name}}
		pcall(function() myDataStore:SetAsync(player.UserId, data) end) 
	end
end

-- Example usage:
game.Players.PlayerAdded:Connect(giveRandomTool)

The code before us shows the exact inverse of your post: you’re refusing to give a tool to a player if they have one in their data-store. Instead, you give the player a random tool when no tool is known to be stored, then update the database to store that random tool. The only issue I see in your code from that point is your calling of Humanoid:EquipTool via the dot operator. EquipTool is a method and should therefore be invoked with the colon (:) operator where possible:

player.Character:WaitForChild("Humanoid"):EquipTool(randomTool)

Note that this will not ensure the tool remains with the player throughout the game, as dying without the tool stored in the player’s “StarterGear” folder would cause that player to lose the tool for the remainder of their time in the server

1 Like

well i was trying to make a script that would give one random player one random tool that they own from there datastore

1 Like

well i was trying to make a script that would give one random player one random tool that they own from there datastore

1 Like

It’s one random player now? I thought you wanted a random tool from a player’s inventory to be given to them every time they joined the game

1 Like