Generally, follow the C# Coding Conventions from MSDN. The following are highlights and small changes to these conventions to better accomodate Unity development:
- Use
_underscoreCamelCase
for private variables to avoid local variable conflicts. Avoid ‘this.variable’ - Use
PascalCase
for methods and public properties. - Use
MyMethodAsync
for async methods which return a Task.
Prefer private fields with public getter / setters. To show private properties in the editor, use [SerializeField]
:
[SerializeField]
private int _myInt;
public int MyInt
{
get => _myInt;
set => value = _myInt;
}
// Public-getter-only example
[SerializeField]
private int _myInt;
public int MyInt => _myInt;
Use Property<T>
and IProperty<T>
for any value that needs to notify that it can change, especially when binding to UI:
[SerializeField]
private Property<int> _myIntProperty;
public IProperty<int> MyIntProperty => _myIntProperty;
private void ChangeTheValue(int newValue)
{
_myIntProperty.Value = newValue;
}
- Group public getter/setter with its private data.
- Leave a blank line between property groups and serialized fields.
- Follow MSDN layout conventions
- Use the standard async / await pattern.
- Using
await
while on the main thread in Unity will always continue back on the main thread. This is unique to Unity's async implementation. If you need to get onto the main thread, useawait Awaiters.UnityMainThread
. - Avoid
Task.Run
unless you really need it. Task.Run runs a block of code on a worker thread and is useful if you have expensive work that you don't want to run on the main thread. However, most of the time, there is already an async function you can use to do expensive work. For example, to read a file, you can useFile.ReadAllTextAsync
. There is no need to invoke this method on a worker thread because will already do its work on a background thread. - For WebGL builds, Avoid using
Task.Delay
. This method runs on a seperate thread, but browsers only support the main thread. - Avoid mixing coroutines and async/await. Coroutines are best for handling user interactions and animations. Async/await is better for interacting with external async code.