JetBrains / JetBrains/resharper-unity

Static code analysis for detecting race conditions in Unity

Open
#1,422 0 comments 0 reactions 1 assignee Claimed by @krasnotsvetov View on GitHub
Dominant language
C#
Stars
1.2k
Forks
142
PR merge metrics
No merged PRs in 30d

Description

This is a suggestion for a new kind of static code analysis rule that will help detecting certain cases of a race condition for Unity developers.

I will try to illustrate my suggestion with an example:

```
public class MyBehaviour : MonoBehaviour
{
void Awake()
{
if (MyOtherBehaviour.Instance.X > 0)
{
// Do Something
}
}
}

public class MyOtherBehaviour : MonoBehaviour
{
public static MyOtherBehaviour Instance;
public int X;

void Awake()
{
Instance = this;
}
}

```
In Unity, Awake is automatically called by the runtime on **all components on game objects** in the scene. There's no particular order of invocation as far as i'm aware, (apart from cases where the order is set in the player settings), but all Awake method are called when the scene loads.

In the code example above, a static Instance property is set up in the Awake of one MonoBehaviour, but is used in the Awake method of another MonoBehaviour.

Since the order that Awake methods are called is not defined, this code may result in a NullReferenceException, or even worse - it may work for a long time before starting to suddenly fail.

Since Rider can detect where a particular field is being assigned from, we can create a rule that will:

- determine if a (Unity) serialized field is set only from the Awake method
- determine if another component accesses (reads) that field's value in its Awake method

In such a case - we should raise a warning, since the behaviour is not defined and may result in an exception at runtime.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.