I have been entertaining the idea of an RTS game for a while, now. Today I came upon a certain dilemma: code organization.
Specifically, I am working on the code that will manage selecting units. It works, but I’m not sure if it could be organized in a better fashion.
I’m not super inclined to reveal my code, but I’ll give some pseudocode on what it’s supposed to do, as well as elaborate on where my code is located:
local function selectUnit(unit)
if the unit actually exists then
add the unit to a list that stores all units currently selected by the player
add a health bar that displays over the unit
recalibrate the main screen of the command bar
recalibrate the possible commands on the command bar
end
end
local function deselectUnit(unit)
if the unit is in the list of selected units then
take the unit out of the list
get rid of the health bar
recalibrate the main screen of the command bar
recalibrate the possible commands on the command bar
end
end
local function deselectAll()
(essentially just uses deselectUnit() on all units currently selected)
end
when the player clicks the left mouse button:
if the mouse was aiming at a unit then
selectUnit(unitHoveredOver)
else
deselectAll()
end
end
when the player clicks the right mouse button:
if the player has any units selected then
invoke a remoteFunction to give the selected units their orders
end
end
In my original setup, there is a local script in StarterPlayerScripts that handles the user’s mouse actions. When the local script finds that a unit has been clicked on, it calls on a module script to index the unit in a ‘selectedUnits’ list. That module script then calls on another module script to add the health bar to the player’s gui. (Both of these modules are in ReplicatedStorage, by the way.)
However, I discovered that I could also just put all the code, including binding the mouse to certain actions, into a single module script, thus reducing the local script to hardly more than a line or two of code (to call on said module). I can’t see any immediate reason why this would be considered bad practice, but it’s such a jump from my original setup that I had to take a step back and think. What is the best setup? When is it appropriate to make another module script? Should I just put some local scripts in my GUI that automatically recalibrate the command bar?
If this changes anything, I have a loose personal guideline to avoid having any script with more than 200 lines (excluding comments). Like I said, though, it’s a loose guideline.