Why does instantiating a ScriptableObject derived class using 'new' keyword throw a warning?

When trying to create an instance of a class derived from ScriptableObject using the ‘new’ keyword, a warning shows up in the console, suggesting to use ScriptableObject.CreateInstance instead.

In the following warning, I’ve substituted the actual class names for X, Y and ActualScript. In my particular case, X derives from ScriptableObject, Y derives from X, and the Update function of ActualScript is where class Y has been instantiated.
This is the warning I receive:
Y must be instantiated using the ScriptableObject.CreateInstance method instead of new Y.
UnityEngine.ScriptableObject:.ctor()
X:.ctor()
Y:.ctor()
ActualScript:Update() (at Assets/Code/ActualScript.cs:22)

It works absolutely fine with the ‘new’ keyword. What is the difference? Is there any particular reason why using the ‘new’ keyword is not recommended in this case? The documentation page isn’t very informative.

I believe it’s along the same principles as not using new for Components, there are “things” that the unityengine needs to do to make sure it’s going to work as expected, by calling new instead of createInstance you are not allowing those “things” to happen…

I’m sure one of the people who know more about how the unity engine actually works will be able to fill in what “things” are, I’m still fuzzy on that (as you can probably tell :slight_smile: )

ScriptableObject has its own constructor, which calls a method on the C++ to that does some unity magic. Someone from Unity will have to explain what it does, as we have no access to the source code. I would Imagine that it registers these objects into all sort of data structures, marks them for GC, performs whichever serialization is needed and so on.

The fact it works doesn’t necessarily mean that everything you need from will work as you develop your class.

Ultimately, it is just syntax. And using CreateInstance as opposed to new will give you what you want and make sure you are complying with the limitations of the engine.

3 Likes