Version: Unity 6 (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.

Additional resources

JSON Serialization
Serialization best practice
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961