Hello!
Goal:
I am new to object-orientated programming and currently trying to find a way for the client to get data from objects created by the server.
Strategy:
I made a table that adds all the created objects when a character spawns and allows the player to get the data with a remote function with the object’s name and function name to call as the parameters.
Issue:
The problem is every time I invoke the server it says the global variable “self” returns nil. I have search through multiple forum topics but still no fix.
Scripts:
Server:
local ps = game.Players
local carClass = require(game.ReplicatedStorage.CarClass)
local func = game.ReplicatedStorage.RemoteFunction
ps.PlayerAdded:Connect(function(p)
local objs = {}
p.CharacterAdded:Connect(function(c)
-- Variables
local humanoid = c.Humanoid
-- Objects
local newCar = carClass.new()
objs.Car = newCar
-- Events
humanoid.Died:Connect(function()
for i,v in pairs(objs) do
v:Remove()
end
objs = {}
end)
func.OnServerInvoke = function(player, params)
-- Player is trying to get data..
local name = params.Name -- Object name
local funcName = params.Function -- Function name
local object = objs[name] -- Finding the object
if object and object[funcName] then -- If both the object and function exist..
return object[funcName]()
else
if object and not object[funcName] then
warn('THERE IS NOT FUNCTION D;')
else
warn('THIS OBJECT DOESNT EXIST D;')
end
end
return nil
end
end)
end)
Local Script:
local func = game:GetService("ReplicatedStorage"):WaitForChild("RemoteFunction")
local makeYear = func:InvokeServer({
Name = "Car";
Function = "GetYear"
})
print(makeYear)
Module:
local CarClass = {}
CarClass.__index = CarClass
function CarClass.new()
return setmetatable({
-- Memebers:
Model = "Toyota";
Made = 2013
},CarClass)
end
function CarClass:GetYear()
return self.Made
end
function CarClass:Remove()
self.Model = nil
self.Made = nil
end
return CarClass
Error: