Listening for Client Input OOP

-- CLIENT SCRIPT --

--// SERVICES \\--
local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

--// VARIABLES \\--
local remoteEvents = ReplicatedStorage:WaitForChild("RemoteEvents")
local digEvent = remoteEvents:WaitForChild("DigEvent")

UserInputService.InputBegan:Connect(function(input, gameProcessedEvent)
	if input.KeyCode == Enum.KeyCode.F and not gameProcessedEvent then
		digEvent:FireServer()
	end	
end)

-- MODULE SCRIPT (SERVER) -- 
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remoteEvents = ReplicatedStorage.RemoteEvents
local digEvent = remoteEvents.DigEvent

local Digsite = {}
Digsite.__index = Digsite

function Digsite.new(tycoon, instance)
	local self = setmetatable({}, Digsite)
	
	self.Tycoon = tycoon
	self.Instance = instance
	self.Owner = tycoon.Owner
	
	return self
end

function Digsite:Init()
	self:ListenForDig()
end

function Digsite:ListenForDig()
	digEvent.OnServerEvent:Connect(function(player)
		if self.Owner == player then
			print("This is the tycoon owner")
		end
	end)
end

return Digsite

I’m currently using OOP and I’m not sure how I can listen for input from the client properly.

How the system works so far is the player steps on a pad and another script creates the object and calls Digsite:Init() externally.

When Digsite:Init() is called and the player presses F once it prints "This is the tycoon owner" once.

However, if the player presses F repeatedly before stepping on the pad, it prints "This is the tycoon owner" however many times the player had pressed F previously.

What am I doing wrong?

Any help is appreciated.

This is occuring due to remoteevents queuing up on the server.

Remote Event Queuing


So basically when you fire a remoteevent, if no handler/callback is specified to recieve it, it will hang around in the memory of the recipient (client or server) until a handler/callback is defined, after which it will pass through all the cached remoteevents and then only flush it out of memory. A large number of remoteevents being cached in a small period of time will result in the remoteevent invocation queue exhaustion error.

Solution


You can call the :ListenForDig function when the object is created and then using a private variable inside the object, preferably named _isInitialized (set to false by default), check if it is set to false, and if yes, return out of the function. Now to make this work, one final step is required: When you call the :Init function, set the above said variable to true.

2 Likes