How to use return in a server script to return data to a client script?

Hello!
Ive been working on my game, and I wanted to clone a weapon.
However, I cannot assign the weapon from the client, or else it will return to nil.
I need to fix this.

I have used stuff like ReplicatedStorage:WaitForChild(weaponname) , but thats not reliable and I need to use a different method.

This is what I want:

--Server 
local function returnWeaponInvoke(player, weapon)
	local weaponClone = weapon:Clone()
	return weaponClone 
end
--Client
local weapon:Model = returnWeaponClone:InvokeServer(weaponToClone) 

However, it returns nil unless I do this:

--Server
local function returnWeaponInvoke(player)
	local weaponClone = replicatedStorage.weapon:Clone() -- doesnt need an argument because it would be assigned here
	return weaponClone 
end 
--Client
local weapon:Model = returnWeaponClone:InvokeServer() --Dont need to add an argument

I dont want this. I want the weapon to be assigned on the client, then returned a clone for future usage.
Any help is appreciated.

Why is WaitForChild not reliable?

Chances are you need to set the parent before you can return some objects. The client and server need to agree where an object is before they can talk to each other about it.

Because I dont want to wait for child on a random string, and besides, all the weapons are in different folders, so I wont be able to tell if its a ranged weapon, or a melee weapon

You could use FindFirstChild so you aren’t waiting around, can even tell it to check descendants so folder depth doesn’t matter. I don’t know your full use case but please try to avoid RemoteFunctions as much as possible. I am confident there is a way around using remote functions in this case.

Thanks for your effort, but I just realized im an idiot :man_facepalming:

apparently, you have to set the parent of the clone to something before returning it.

in my example, i didnt set the parent of the clone to anything, but when I did, I set it to replicated storage then returned the clone,

FOR SOME REASON, the code didnt print nil

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.