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.
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.
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.
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)
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).