# スクリプトシリアライズエラー

> Diagnose and fix common script serialization errors in your project.

特定の状況では、スクリプトのシリアル化によってエラーが発生する可能性があります。その一部について、修正方法を以下にリストアップします。

## Unity スクリプティング API をコンストラクターやフィールドイニシャライザーから呼び出す

[MonoBehaviour](/engine/6000.0/script-reference/unity-engine/mono-behaviour.md) のコンストラクターやフィールドイニシャライザー内で [GameObject.Find](/engine/6000.0/script-reference/unity-engine/game-object/find.md) などのスクリプティング API を呼び出すと、エラー "Find is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call in Awake or Start instead. (Find は MonoBehaviour コンストラクタ― (またはインスタンスフィールドイニシャライザー) から呼び出すことはできません。代わりに Awake または Start で呼び出してください。)" が発生します。

この修正には、コンストラクター内ではなく、[MonoBehaviour.Start](/engine/6000.0/script-reference/unity-engine/mono-behaviour/start.md) 内でスクリプティング API を呼び出します。

## 逆シリアル化中の Unity スクリプティング API の呼び出し

`System.Serializable` でマークされたクラスのコンストラクター内から [GameObject.Find](/engine/6000.0/script-reference/unity-engine/game-object/find.md) などのスクリプティング API を呼び出すと、エラー "Find isn't allowed to be called during serialization, call it from Awake or Start instead.” (Find はシリアル化中に呼び出すことはできません。代わりに Awake または Start で呼び出してください。)" というエラーが発生します。

これを修正するには、シリアル化されたオブジェクトに対するスクリプティング API の呼び出しが、コンストラクター内で一切行われないように、コードを変更します。

## スレッドセーフな Unity スクリプティング API

スクリプティング API の多くは、上記の制限の影響を受けます。一部の Unity スクリプティング API のみ、例外的に影響を受けず、どこからでも呼び出すことができます。該当する API は以下の通りです。

* [Debug.Log](/engine/6000.0/script-reference/unity-engine/debug/log.md)

* [Mathf](/engine/6000.0/script-reference/unity-engine/mathf.md) 機能

* 単純な自己完結型構造体 (例えば [Vector3](/engine/6000.0/script-reference/unity-engine/vector-3.md) や[クォータニオン](/engine/6000.0/script-reference/unity-engine/quaternion.md)などの数学構造体)

シリアル化でのエラーのリスクを軽減するために、呼び出す API メソッドは、Unity からのデータの取得や Unity でのデータの設定が不要な自己完結型のみとしてください。また、代わりの方法がない場合にのみ呼び出すようにしてください。

## 追加リソース

* [シリアル化のルール](/engine/6000.0/manual/scripting/compilation-and-code-reload/script-serialization/rules.md)
* [Unity がシリアル化を使用する方法](/engine/6000.0/manual/scripting/compilation-and-code-reload/script-serialization/how-unity-uses.md)
* [JSONSerialization](/engine/6000.0/manual/scripting/compilation-and-code-reload/script-serialization/json-serialization.md)
* [シリアル化のベストプラクティス](/engine/6000.0/manual/scripting/compilation-and-code-reload/script-serialization/best-practices.md)
