unity runtime_error ai_generated true

InvalidOperationException: It is not allowed to create a ScriptableObject from the constructor

ID: unity/scriptableobject-constructor-called

Also available as: JSON · Markdown · 中文
93%Fix Rate
88%Confidence
1Evidence
2024-03-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Unity 2022.3 active
Unity 2023.1 active
Unity 2023.2 active

Root Cause

A ScriptableObject instance was created using the 'new' keyword in a constructor instead of ScriptableObject.CreateInstance.

generic

中文

在构造函数中使用了 'new' 关键字创建 ScriptableObject 实例,应使用 ScriptableObject.CreateInstance。

Official Documentation

https://docs.unity3d.com/ScriptReference/ScriptableObject.CreateInstance.html

Workarounds

  1. 98% success Replace 'new MyScriptableObject()' with 'ScriptableObject.CreateInstance<MyScriptableObject>()'.
    Replace 'new MyScriptableObject()' with 'ScriptableObject.CreateInstance<MyScriptableObject>()'.
  2. 95% success If you need to initialize fields, create a static factory method that calls CreateInstance and then sets properties.
    If you need to initialize fields, create a static factory method that calls CreateInstance and then sets properties.

中文步骤

  1. Replace 'new MyScriptableObject()' with 'ScriptableObject.CreateInstance<MyScriptableObject>()'.
  2. If you need to initialize fields, create a static factory method that calls CreateInstance and then sets properties.

Dead Ends

Common approaches that don't work:

  1. 95% fail

    ScriptableObject must be created via CreateInstance, not by new, regardless of serialization attributes.

  2. 85% fail

    ScriptableObject requires explicit initialization via CreateInstance to set up internal Unity engine state.