OOP returning self nil

Im trying to make a system that will handle spaceships, so I made a local script to send inputs to a server module script, but for some reason the ship keep returning nil in the Start function but prints just fine in the constructor function. Im stumped, any ideas?

Server Module:

local RNS = game:GetService("RunService")
local RS = game:GetService("ReplicatedStorage")
local InputEvent = RS.ShipInputs

local ShipServer = {}
ShipServer.__index = ShipServer
function ShipServer.NewShip(plr,ship)
	local self = setmetatable({
		Owner = plr,
		Ship = ship,
		Speed = 0,
		Connection = nil,
		
	},ShipServer)
	print(self.Ship)
	return self
	
end

function ShipServer:Start()
	print(self.Ship)
	InputEvent.OnServerEvent:Connect(function(plr,input,state)
		if state == 1 then
			print(input)					
			local value = Instance.new("IntValue",self.Ship)	
			value.Name = input
		end
	end)
end

return ShipServer

Local script (temporary):

local RS = game:GetService("ReplicatedStorage")
local Plrs = game:GetService("Players")
local UIS = game:GetService("UserInputService")

local plr = Plrs.LocalPlayer

local ShipEvent = RS.StartShip
local InputEvent = RS.ShipInputs
local ShipClient = require(RS.ShipClient)

ShipEvent.OnClientEvent:Connect(function(state)
	if state == 1 then
	ShipClient.Start()
	UIS.InputBegan:Connect(function(input)
		InputEvent:FireServer(input.KeyCode,1)
	end)
	UIS.InputEnded:Connect(function(input)
		InputEvent:FireServer(input.KeyCode,2)
		end)		
	else	
	end
end)

First of all, before running an event on ShipClient, make the actual Ship first with your constructor.
That’s where you run methods / functions, not the module itself.

(e.g)

local ShipEvent = RS.StartShip
local ShipModule = require(RS.ShipClient)

local myNewShip = ShipModule.NewShip(plr, ship)

ShipEvent.OnClientEvent:Connect(functon(state)
     ...
     myNewShip:Start() -- NOT myNewShip.Start(), :Start() supplies self as the first argument, .Start() is a basic function
     -- myNewShip.Start(myNewShip) | this is what the equivalent without : would be
end)
1 Like

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