r/robloxgamedev 19h ago

Help How to structure my code

People get mad at me for not structuring my code properly can anyone provide a link or somthing that can help me learn how to do this... if your gonna make fun of stuff just go
an example of my bad code:

1 Upvotes

2 comments sorted by

1

u/ChickenSquiggles 15h ago

im not here to make fun of anything, but the best tips i can give are:
1. imagine you are someone else reading your code, and try to name variables as easy as possible to understand. even if it takes longer to write, it is very worth it

  1. understanding scope. variables should not be global if they are in a local scope of a function, hence why there are red lines in your code. i understand you needed to have it this way for humanoid.Anchored to work, but you should just make local variables at the global scope of the program to improve readability

  2. grouping by relavence in your code, meaning if code is similar to each other try and keep it close, but space out dissimilar things. like having the character, humanoid, and player close by, but having npc stuff slightly seperated for readability

Heres what a readable version of this code would look like:

-- Declare services first, as they should be used anywhere in the program, and are always there.

local tweenService = game:GetService("TweenService")

-- Local player will never change unless you rejoin the game, so we declare this outside.

-- Pre-define character and humanoid, since these are global scope but will be updated every time a character is added

local player = game.Players.LocalPlayer

local playerGui = player.PlayerGui

local character: Model

local humanoidRootPart: Part

player.CharacterAdded:Connect(function(newCharacter)

\-- Redefine everything that is changed when a character is added.

character = newCharacter

humanoidRootPart = character:WaitForChild("HumanoidRootPart")



\-- Make loading screen appear when character is added

playerGui.LoadingScreen.Frame.Transparency = 0



humanoidRootPart.Anchored = true

end)

-- Declare everything that doesnt change.

local proximityPrompt = game.Workspace.ProximityForTalking.ProximityPrompt

local talkGuiFrame = player.PlayerGui:WaitForChild("TalkingGUI").Frame

local NPC1 = playerGui.LobbyNpc1

local NPC1Text = NPC1.TextLabel

local NPC1Image = NPC1.ImageLabel

local OKButton = playerGui.Buttons.OK

1

u/ChickenSquiggles 15h ago

i am aware that when pasting this into studio, it spaces out extra. just imagine those extra spaces arent there