You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
As a programmer, it is very important to follow a coding standard and make sure others can read and easily understand his code. While there’s not majority guideline of coding standard in Unity and C#, [you can/should code whatever you like](http://wiki.c2.com/?UncleBobOnCodingStandards), but in this article I’m going to show you our style and format guideline within the company. We have tried to adopt different styles throughout these years and came out the one we feel most comfortable.
5
+
As a programmer, following a coding standard is crucial to ensure code readability and understandability. While Unity and C# lack a definitive coding standard, you have the [freedom to code as you prefer](http://wiki.c2.com/?UncleBobOnCodingStandards). In this article, we present our internal style and formatting guidelines developed over the years to create a comfortable coding environment.
6
6
7
-
Our **3 golden rules**to forms our style standard:
8
-
1.Follow Unity’s style in [Scripting Reference](https://docs.unity3d.com/ScriptReference/)
3.Minor tweak where we believe that can make the code clearer
7
+
Our **3 golden rules**shape our style standard:
8
+
1.Adhere to Unity's style as described in the [Scripting Reference](https://docs.unity3d.com/ScriptReference/).
9
+
2.Follow Microsoft's [C# Coding Conventions](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions)for the rest.
10
+
3.Implement minor tweaks to enhance code clarity.
11
11
12
12
#### Folder Structure
13
13
14
-
All similar files should be grouped in the root folders:
14
+
Group similar files in root folders:
15
15
16
16
```
17
17
Assets
18
18
Animations Animation clips
19
-
Editor Editorspecified scripts, prefabs, etc
20
-
Fonts Fonts used in game
19
+
Editor Editor-specified scripts, prefabs, etc
20
+
Fonts Fonts used in the game
21
21
Materials Texture materials
22
22
Prefabs In-game prefabs
23
23
Resources Unity resources assets
24
24
Scenes Scenes
25
-
Scripts Code scripts, grouped in sub-folders
25
+
Scripts Code scripts, organized in sub-folders
26
26
Sounds Musics, sounds
27
-
SweatyChairCompany folder that share across projects
28
-
(ModuleName1) Module name, e.g. DailyLogin
29
-
(Scripts) Scripts within the module
30
-
(Prefabs) Prefabs within the module
27
+
<CompanName> Company folder shared across projects
28
+
<ModuleName> Module name, e.g. DailyLogin
29
+
Scripts Scripts within the module
30
+
Prefabs Prefabs within the module
31
31
... Other assets grouped in folders
32
32
... Other modules
33
33
Textures Image textures
34
34
UI Texture used for UI
35
35
Icons App icons
36
36
```
37
37
38
-
> We have a `SweatyChair` folder, which containes a number of well-structure modules and sync across projects using Git [submodules](https://www.git-scm.com/book/en/v2/Git-Tools-Submodules). We we are always reuse the commond code and able to perform rapid prototyping.
38
+
> We maintain a `<CompanyName>` folder containing well-structured modules that sync across projects using Git [submodules](https://www.git-scm.com/book/en/v2/Git-Tools-Submodules). This approach allows us to reuse common code and facilitate rapid prototyping.
39
39
40
40
#### File Naming
41
41
42
-
File naming is simple, always use Pascal Case except for images:
42
+
File naming is straightforward, always use PascalCase except for images:
- Images use hyphen naming: `image-name-64x64.jpg`
46
+
- The rest uses PascalCase: `ScriptName.cs`, `PrefabName.prefab`, `SceneName.unity`
50
47
51
-
> The reason images use hyphen naming is that most images are also used in our website / press-kit. Hyphen naming is the majority naming convention for web image and it’s also [search engine friendly](https://www.natalleblas.com/optimise-images-for-seo/). Using the same name can save us time renaming and easily find the same image switching between Unity and web.
48
+
> Images are often given hyphenated names because they are commonly used in both our website and presskit. Hyphenated naming is the prevailing convention for web images and is also favorable for [search engine optimization](https://www.natalleblas.com/optimise-images-for-seo/). Employing consistent names allows us to save time by avoiding the need for renaming and makes it effortless to locate the same image when transitioning between Unity and the web.
52
49
53
50
#### Scripts Naming
54
51
55
-
While each script has its unique purpose and use cases, we follow these naming rules and so we can still roughly know what the script is for by simply reading the filenames:
52
+
Scripts follow specific naming rules to convey their purpose:
56
53
57
-
-`XxxPanel`, `XxxSlot`, `XxxButton`, etc for UI
54
+
-`XxxPanel`, `XxxSlot`, `XxxButton`, etc for UI:
58
55
`MenuPanel`, `AchievementSlot`, `CoinShopButton`
59
-
-`XxxManager`, for master scripts that control specific workflow (only ONE instance in the scene)
56
+
-`XxxManager`, for master scripts controlling specific workflows (only ONE instance in the scene):
60
57
`DailyMissionManager`, `AchievementManager`
61
-
-`XxxController`, for scripts controlling a game object (one or many in the scene)
58
+
-`XxxController`, for scripts controlling a game object (one or many in the scene):
-`XxxDatabase`, for a database (e.g CSV) which contains a list of data rows
60
+
-`XxxDatabase`, for a database (e.g. CSV) containing data rows:
64
61
`WeaponDatabase`, `CardDatabase`
65
-
-`XxxData`, for data row in a CSV database
62
+
-`XxxData`, for data rows in a CSV database:
66
63
`WeaponData`, `CardData`
67
-
-`XxxItem`, for in-game item instance
64
+
-`XxxItem`, for in-game item instances:
68
65
`CardItem`, `CharacterItem`
69
-
-`XxxGenerator`, for scripts instantiate GameObjects
66
+
-`XxxGenerator`, for scripts instantiating GameObjects:
70
67
`ObjectGenerator`, `LandGenerator`
71
-
-`XxxSettings`, for settings scripts inherent Unity’s [`ScriptableObject`](https://docs.unity3d.com/Manual/class-ScriptableObject.html) class
68
+
-`XxxSettings`, for settings scripts inherent to Unity's [`ScriptableObject`](https://docs.unity3d.com/Manual/class-ScriptableObject.html) class:
72
69
`AchievementSettings`, `DailyLoginSettings`
73
-
-`XxxEditor`, for editor-only scripts inherent Unity’s `[Editor](https://docs.unity3d.com/ScriptReference/Editor.html)` class
70
+
-`XxxEditor`, for editor-only scripts inherent to Unity’s `[Editor](https://docs.unity3d.com/ScriptReference/Editor.html)` class:
74
71
`TutorialTaskEditor`, `AchievementSettingsEditor`
75
72
76
-
> Difference between `Manager` and `Controller`is `Manager` should be singleton or static, and it controls a specific game logic that may involve multiple objects and assets, while Controller controls an object and may have multiple instances. For example, there are multiple EnemyController in the scene and each control one enemy. We will discuss more on this in a singleton article.
73
+
> The distinction between a `Manager` and a `Controller`lies in the fact that a Manager should typically be implemented as a singleton or static entity, overseeing specific game logic that may involve multiple objects and assets. In contrast, a `Controller` is responsible for governing an individual object and can have multiple instances. For instance, within a scene, there may be several `EnemyController`s, each managing a distinct enemy. We will delve deeper into this topic in an upcoming article dedicated to singletons.
77
74
78
-
> Difference between `Data` and `Item` is that `Item`is an instance in-game, and in most cases`Item` contains a `Data`. For example `CardData`has all preset attributes of a card, while `CardItem`has its`CardData`plus attributes that vary for different players, such as card level. We will talk about more this in another data structure article.
75
+
> The differentiation between `Data` and `Item` is that an `Item`represents an in-game instance, and in most cases, it encapsulates a `Data` component. For example,`CardData`encompasses all the preset attributes of a card, while `CardItem`incorporates the`CardData`and additional attributes that vary for different players, such as the card's level. We will explore this concept further in another article focused on data structures.
79
76
80
77
#### Variable Naming
81
78
82
-
Similar to file naming, variable naming allow us to know what the variable is for without reading though all code:
79
+
Variable naming uses camelCase to convey their purpose without needing to read through all the code:
83
80
84
-
- Use camcelCase, always as of a noun or in a form of (is/has)Abjective
85
-
`hasRewarded`, `currentPosition`, `isInitialized`
86
-
- Prefix with an underscore for private and protected variables
81
+
- Prefix with an underscore for private and protected variables:
- Use xxxxList for List and xxxxDict for Dictionary
99
+
- Use xxxxList for `List` and xxxxDict for `Dictionary`:
105
100
`weaponTransformList = new List()`
106
101
`achievementProgressDict = new Dictionary()`
107
-
- Use nounVerbed for callback event
102
+
- Use nounVerbed for callback event:
108
103
`public static event UnityAction gameStarted`
109
104
`public static UnityAction characterDied`
110
105
111
-
> Unity use prefix `m_`for private/protected variables, and `s_`for static variables (see their [BitBucket](https://bitbucket.org/Unity-Technologies/assetbundlegraphtool/src/0e498d12964d7cd1b86728289ff6f8321d127db4/Runtime/AssetBundleBuildMap.cs)). We found that this makes the code very hard to read, so we leave one underscore for private/protected variables and keep it the same for both static and non-static variables.
106
+
> In Unity, the convention for naming private/protected variables is to use the prefix `"m_"` and for static variables, `"s_"` (as indicated in their [BitBucket](https://bitbucket.org/Unity-Technologies/assetbundlegraphtool/src/0e498d12964d7cd1b86728289ff6f8321d127db4/Runtime/AssetBundleBuildMap.cs)). However, we've observed that this practice can make the code less readable. As a result, we have adopted a simplified approach by using a single underscore "_" for both private/protected and static variables to enhance code clarity.
112
107
113
108
> Callback event follow Unity’s event naming convention, e.g. `[SceneManager.activeSceneChanged](https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-activeSceneChanged.html)`.
114
109
115
110
#### Functions Naming
116
111
117
-
-Use PascalCase, start with a verb and followed by a noun if needed
112
+
-Functions use PascalCase, starting with a verb and followed by a noun if necessary:
118
113
`Reward()`, `StartGame()`, `MoveToCenter()`
119
-
-Use `OnXxxxClick`, for UI button clicks
114
+
-Callback functions for UI button clicks are named as `OnXxxClick`:
120
115
`OnStartClick()`, `OnCancelClick()`
121
-
-Use `OnNounVerbed`, for callbacks
116
+
-Callback functions use `OnNounVerbed`:
122
117
`OnChestOpened()`, `OnBuyWeaponConfirmed()`
123
118
124
119
#### Member Properties
125
120
126
-
If a function has no input, use member property (aka get/set property) instead, in PacelCase as well:
127
-
`bool IsRewarded() { }`
128
-
to
121
+
If a function has no input, use a member property (get/set property) in PascalCase:
129
122
`bool IsRewarded {get { return …} }`
130
-
Or even in a shortened form as
123
+
Or
131
124
`bool IsRewarded => ...;`
132
125
133
-
Also, use member properties where a variable can only set internally but can be accessed publicly:
126
+
Member properties are used where a variable can only be set internally but accessed publicly:
134
127
`public int Id { get; private set; }`
135
128
`public Sprite IconSprite { get; private set; }`
136
129
137
130
#### Variables / Functions orders
138
131
139
-
Having a consistent order can greatly save our time on looking for a specific variable or function:
132
+
Consistent order saves time searching for specific variables or functions. Here's the preferred order:
140
133
141
134
```
142
135
MyCalss : Monobehavior
@@ -187,7 +180,7 @@ MyCalss : Monobehavior
187
180
}
188
181
```
189
182
190
-
You can also group valuables and functions in a region in large scripts (but not too large enough to be split into another script):
183
+
You can also consider grouping variables and functions within a region in larger scripts, but ensure that the script remains manageable and doesn't become overly extensive, to the point where it should be split into multiple scripts. This can help improve code organization and readability.
191
184
192
185
```
193
186
#region Timer
@@ -204,11 +197,11 @@ You can also group valuables and functions in a region in large scripts (but not
204
197
205
198
#### Code Formatting
206
199
207
-
We use **K&R** style which is already preset in Mac Visual Studio:
200
+
We use **K&R** style, which is preset in Mac Visual Studio:
@@ -220,7 +213,7 @@ While there’s not K&R in Windows (Why, Microsoft?), just a little bit effort t
220
213
221
214
#### Brackets and Newlines
222
215
223
-
For single-line conditional statements we do not need any brackets:
216
+
For single-line conditional statements, no brackets are needed:
224
217
225
218
```
226
219
if (1 == 1)
@@ -232,7 +225,7 @@ if (1 == 1) {
232
225
}
233
226
```
234
227
235
-
> Many developers, includes Unity, favourite putting newlines after open bracket ( `{` ). It may make the code looks more tidy and symmetric, but also creates a lot of unuseful lines and making script scrolling much more often and longer. Every bit count. If you spend 1 more second on scrolling a day, you probably wasted 5 minutes of valuable time a year.
228
+
> Numerous developers, Unity included, have a preference for inserting newlines after an open bracket "{." While this practice can lend a sense of tidiness and symmetry to the code, it can also generate numerous unnecessary lines, leading to more frequent and longer script scrolling. Every bit of efficiency matters, as even spending an extra second on scrolling each day can add up to wasting five minutes of valuable time over the course of a year.
236
229
237
230
#### Comments
238
231
@@ -245,4 +238,4 @@ Temporarily commenting out code should not include a space after the slashes, to
245
238
246
239
----------
247
240
248
-
That’s all. This may go bigger when you adopt more latest .Net syntax. There are also a few other good [guidelines](https://github.com/justinwasilenko/Unity-Style-Guide)if you want to read [more](http://www.arreverie.com/blogs/unity3d-best-practices-folder-structure-source-control/). Free feel to follow this style if you think it’s reasonable and helpful, so we may create a better game dev world where code is clean and please to read. 😀
241
+
That concludes our coding guideline. It's worth noting that these guidelines may expand as you incorporate more recent .Net syntax. If you're interested in further best practices, there are additional valuable [guidelines](https://github.com/justinwasilenko/Unity-Style-Guide) to [explore](http://www.arreverie.com/blogs/unity3d-best-practices-folder-structure-source-control/). Feel free to embrace this coding style, as it promotes clean and readable code, contributing to the enhancement of the game development community. 😊
0 commit comments