JetBrains / JetBrains/resharper-unity
Warn on using non-thread safe APIs during Object construction/serialisation
- Dominant language
- C#
- Stars
- 1.2k
- Forks
- 142
- PR merge metrics
- No merged PRs in 30d
Description
The Unity serialiser runs on a different thread to the rest of the Unity API, which means that it is not safe to call into most Unity APIs when an object is being serialised or deserialised. Unity will [report usage of non-thread safe APIs at runtime](https://docs.unity3d.com/2018.2/Documentation/Manual/script-Serialization-Errors.html) - Rider should catch this at edit time and show a warning in code.
Specifically:
* The serialiser will create new instances of classes deriving from `UnityEngine.Object`, on the serialiser's thread. The constructors and instance field initialisers of these classes can only call thread safe APIs.
* The serialiser creates instances of classes marked with `[Serializable]`, so the constructors and instance field initialisers of these classes can only call thread safe APIs.
* The serialiser will also [call methods on the `ISerializationCallbackReceiver` interface](https://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html) for custom serialisation, so these methods should also only call thread safe APIs.
Unity APIs are identified as `extern` methods and properties on classes declared in namespaces under `UnityEngine` and `UnityEditor`. These APIs are not thread safe by default, and should only be called from the main Unity thread. Thread safe APIs are marked with the `[ThreadSafe]` and `[ThreadAndSerializationSafe]` attributes.
Rider should recognise when a non-thread safe API is being called and add a warning, with a message similar to:
> This API is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call in in Awake or Start instead.
or, for custom `[Serializable]` classes or the `ISerializationCallbackReceiver` methods:
> This API is not allowed to be called during serialization, call it from Awake or Start instead
Contributor guide
Assessment
This issue has not been assessed yet.