Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Sometimes remote function returns nil, sometimes it works properly?

I'm trying to pass a set of values from the server to the client when they request it. The four values are charge, maxcharge, downtime, and drain. They are all NumberValues located within a folder under a tool. the localscript is from that tool. Sometimes, this works correctly and there are no problems. However, there are other times where the values are nil. It seems all values are nil, though the error is thrown at charge specifically being nil.

I thought it might be that the NumberValues don't exist yet for the player which might cause replication errors, so there are wait()s above to yield until these exist. However, this was not helpful. I don't understand why this seems to work at random.

--local side
local function statrequest()
	local charge, maxcharge, downtime, drain = game.ReplicatedStorage.StatRequest:InvokeServer()
	return charge, maxcharge, downtime,	drain
end

--server side
local function statrequest(player)
	local Character = player:FindFirstChild("Character")
	if Character then
	local tooltag = Character:FindFirstChild("EquipmentToolTag", true)
		if tooltag then
			local equipstats = tooltag.Parent.equipStats
			print(equipstats.Charge.Value,	equipstats.MaxCharge.Value,	equipstats.FireRate.Value, equipstats.Drain.Value)
			return equipstats.Charge.Value,	equipstats.MaxCharge.Value,	equipstats.FireRate.Value, equipstats.Drain.Value
		end
	end
end
game.ReplicatedStorage.StatRequest.OnServerInvoke = statrequest

1 answer

Whenever you're trying to get a child of something in Client-side, always use :WaitForChild() because the Client loads first before the Server. When trying to get the Character of a Player, use Player.Character because Character is a property of Player, not a child.

--local side
local function statrequest()
	return game:GetService("ReplicatedStorage"):WaitForChild("StatRequest"):InvokeServer()
end

--server side
local function statrequest(player)
	local Character = player.Character or player.CharacterAdded:Wait()
	if Character then
		local tooltag = Character:FindFirstChild("EquipmentToolTag", true)
		if tooltag then
			local equipstats = Character.equipStats
			print(equipstats.Charge.Value,  equipstats.MaxCharge.Value, equipstats.FireRate.Value, equipstats.Drain.Value)
			return equipstats.Charge.Value, equipstats.MaxCharge.Value, equipstats.FireRate.Value, equipstats.Drain.Value
		end
	end
end
game:GetService("ReplicatedStorage").StatRequest.OnServerInvoke = statrequest

2 comments

0

thank you for the effort, but it still errors with waitforchild(). i think its definitely a networking issue though

0

Can I check the error in the output?

This discussion is preserved as it was. New answers, comments, and votes are closed.