Unable to cast value to object error after using a remote event

I am trying to make a function that gives all the players in my game a specific value of money by sending the amount they earn through a remote event and into a TextBox, and whenever I try to run the script, I get the error: Unable to cast value to Object. It said the error was in the ServerScriptService.

Script in ServerScriptService:

function giveMoney(playersToEarn,amount)
	for _, i in ipairs(playersToEarn) do
		local playingID = table.find(playerList,i)
		local player = Players:GetNameFromUserIdAsync(i)
		givePlayerMoney:FireClient(player,amount) -- Sends the values to a TextBox
	end
end

giveMoney(playerList,100) -- Player list is the stored list of player IDs playing

Is playerList an array or a dictionary? An example of what it looks like with data inside would be helpful.

playerList is an array in case you are wondering. It is the IDs of everyone in the game

FireClient expects a player object. Instead of GetNameFromUserIdAsync you should use GetPlayerByUserId .

3 Likes

Whoops. I misunderstood the use. In this case, you might want to loop through all of the players instead of storing their IDs.

local function giveMoney(amount)
	for _,v in pairs(game:GetService("Players"):GetPlayers()) do
		givePlayerMoney:FireClient(v,amount) -- Sends the values to a TextBox
	end
end

giveMoney(playerList,100)

If you are trying to award certain players money and not everyone in a game do the same above but maybe compare the userIDs of the players you loop through to a table of userIDs that you can pass into the function.

3 Likes

Additionally, if you wanted to simplify this even more you could just run :FireAllClients() to fire to all clients automatically without having to loop through each individual one. Ex:

local function giveMoney(amount)
	givePlayerMoney:FireAllClients(amount) -- Sends the values to a TextBox
end

giveMoney(playerList,100)
1 Like