Version: Unity 6 Preview (6000.0)
Language : English
JSON Serialization
Serialization best practice

Script serialization errors

In certain circumstances, script serialization can cause errors. Fixes for some of these are listed below.

Calling Unity Scripting API from constructor or field initializers

Calling scripting APIs such as GameObject.Find inside a MonoBehaviour constructor or field initializer triggers the error: “Find is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call in in Awake or Start instead.”

Fix this by making the call to the scripting API in MonoBehaviour.Start instead of in the constructor.

Calling Unity scripting API during deserialization

Calling scripting APIs such as GameObject.Find from within the constructor of a class marked with System.Serializable triggers the error: “Find is not allowed to be called during serialization, call it from Awake or Start instead.”

To fix this, edit your code so that it doesn’t make any scripting API calls in any constructors for serialized objects.

Thread-safe Unity scripting API

The majority of the scripting API is affected by the restrictions listed above. Only select parts of the Unity scripting API are exempt and may be called from anywhere. These are:

  • Debug.Log

  • Mathf functions

  • Simple self-contained structs; for example math structs like Vector3 and QuaternionUnity’s standard way of representing rotations as data. When writing code that deals with rotations, you should usually use the Quaternion class and its methods. More info
    See in Glossary

To reduce the risk of errors during serialization, only call API methods that are self-contained and do not need to get or set data in Unity itself. Only call these if there is no alternative.


Errors

JSON Serialization
Serialization best practice