arrow-left

All pages
gitbookPowered by GitBook
1 of 2

Loading...

Loading...

Common Patterns and Structure

This section includes some rules of thumb for design patterns and code structure

hashtag
Error handling

Avoid throwing exceptions. Instead log and error. Methods returning values should return null in addition to logging an error

BAD:

GOOD:

hashtag
Finding references

Don't use Find or in other ways refer to GameObjects by name or child index when possible. Reference by reference is less error prone and more flexible. Expect people to set the fields in the inspector and log warnings if they don't.

BAD:

hashtag
RequireComponent

Prefer RequireComponent and GetComponent over AddComponent. Having the components in the inspector let's us edit them. AddComponent limits us.

BAD:

GOOD:

hashtag
Properties with backing fields

Properties can be used for access control to fields, and when using backing fields they can be private and let us change them in the inspector. Consider when a fields should be public and prefer properties with backing fields.

Sometimes it's just nice to see them for debugging, even if we don't change them, so consider making more of your private fields visible.

OKAY:

BETTER:

public List<Transform> FindAThing(int arg){
    ...
    if (notFound) {
        throw new NotFoundException();
    }
}
public List<Transform> FindAThing(int arg){
    ...
    if (notFound) {
        Debug.LogError("Thing not found");
        return null;
    }
}
private GameObject _someMember;

private void Start() {
    _someMember = GameObject.Find("ObjectName");
}
public class : MonoBehaviour
{
    private AudioSource _audioSource;

    private void Start() {
        _audioSource = gameObject.AddCompenent<AudioSource>();
    }
}
[RequireComponent(typeof(AudioSource))]
public class : MonoBehaviour
{
    private AudioSource _audioSource;

    private void Start() {
        _audioSource = GetCompenent<AudioSource>();
    }
}
public GameObject SomeMember;
[SerializeField] private GameObject _someMember;
public GameObject SomeMember => _someMember;

Applying attributes on all network related methods.

Whenever someone add a script implementing NetworkBehaviour, they have access to the following attributes, indicating if a given method should be server only, client only, or both :

  • [Server] for server only code.

  • [Client] for client only code.

  • [ServerOrClient] for both.

Make sure no methods goes without an attribute in a script inheriting NetworkBehaviour. The goal is to increase readability and to generate warnings or exceptions when clients or server are attempting to call something they should not.

Methods with [ServerOrClient] attributes should stay uncommon, they make debugging harder. If possible, try to refactor the code to avoid them.