Gun Using OOP client to server communication

Client → Server Communication Issue with OOP

Let’s say I have a basic OOP Class for a gun.

local Gun = {}
Gun.__index = Gun

function Gun.New()
    ...
end

function Gun:Reload()
    ...
end

For my Gun:Reload() function, Let’s say I have a local script that detects when the player presses R and fires an event. When that event is fired, how do I know which gun the player is trying to reload? how do I know when to run my Gun:Reload() function for the gun object that I created?

I have looked through so many Devforum posts and could not find any that went in-depth about client and server communication with OOP.

2 Likes

OOP in LuaU is really just a bunch of tables. And while it is useful, it has limitations. A table cannot exist on both the client and the server. You may have identical tables on both, but it will never be the same table. As such, you cannot simply pass the object through a RemoteEvent, instead you would need some other way of determining which weapon the client is using. If you are using tools, this could be done by checking which tool the player currently has equipped. Your approach may vary depending on how your game is structured, but it should be along the lines of:

  • Client fires Reload RemoteEvent
  • Server fetches relevant weapon object
  • Server calls the relevant function

There are a multitude if ways to do this, so you should come up with one that fits your needs.

2 Likes

When the server creates a gun, assign it an ID, and send that ID to the client in a remote event. When the client wishes to reload, it fires the reload remote event with that ID, so the server knows what gun the client is talking about and can reload it or do whatever.

3 Likes

Thanks for your help, I understand your method. If you don’t mind answering a question I have, when should I create the gun objects? should I “preload” them and just create gun objects for each player? Should I create the object when a player selects that weapon for their loadout? The way my system works im going to have a primary and a secondary weapon for each player. (Im using tools if this helps in any way)

1 Like

When you create the objects depends on how your game is structured, but I’m going to assume that loadout changes only apply after respawn.

You should be fine destroying all the guns when the player dies and creating them all again on respawn. I can see how the gun classes can get bloated in the future as you continue working on your game, but even still, I don’t think creating gun objects will ever pose performance issues (you’re also only creating 2 per player, which is extremely low).

1 Like

Thank you so much, just tested it out and your way of creating an ID and assigning it to the object works very well

1 Like

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