OOP Class Functions Do Not Work When Using Remote Events

Hello! :smile:

I am trying to implement OOP in a game of mine that I think would benefit from it a lot. In a module script, I have a class “Vehicle” a function of the Vehicle named “spawn,” which spawns a certain vehicle in a workspace. Then, in a localscript, I create a new instance of the Vehicle class, and then, using a remote event, I send the instance to a server script. There, the server script uses the spawn function. However, the server script seems to not recognize the spawn function, despite requiring the Vehicle module, and being able to read the properties of the class instance perfectly fine. Below I have attached the scripts I am using

--Module Script
local Vehicle = {}
Vehicle.__index = Vehicle

local isServer = game["Run Service"]:IsServer()

function Vehicle.new(id)
	local newVehicle = {}
	setmetatable(newVehicle, Vehicle)
	newVehicle.velocity = 0
	newVehicle.id = id
	return newVehicle
end

function Vehicle:Spawn()
	if isServer then
		self.object = game.ServerStorage.carTemplate:Clone()
		self.object.Name = self.id.."car"
		self.object.Parent = game.Workspace
		self.object:SetPrimaryPartCFrame(game.Workspace.spawn.CFrame)
	end
end

return Vehicle

--Local Script

Vehicle = require(game.ReplicatedStorage.vehicleModule)

local plrVehicle = Vehicle.new(game.Players.LocalPlayer.UserId)

game.ReplicatedStorage.spawnVehicle:FireServer(plrVehicle)
--Server Script
Vehicle = require(game.ReplicatedStorage.vehicleModule)

game.ReplicatedStorage.spawnVehicle.OnServerEvent:Connect(function(player,plrVehicle)
	plrVehicle:Spawn()
end)

and the error I get is

ServerScriptService.Script:4: attempt to call missing method 'Spawn' of table  -  Server - Script:4

I tried looking at posts with similar problems, but they all either only had a problem with properties of the class instances, or were nearly identical to my scripts but did not have any problem whatsoever.

Many posts referred to using remote events and RunServer:IsServer(), which I both used here, but never really went in detail about how to use them.

Thanks!

1 Like

Hi there,

If you check out this link, you’ll see that you cannot pass over functions OR metatables over RemoteEvents/RemoteFunctions. This is for security. This means that the Vehicle metatable is completely absent from your newVehicle object.

I would suggest for you to make two OOP objects-- one on the client and one on the server, and then you should be able to go on from there.

Good luck!

1 Like