CreateInstance with constructor?

Hi guys,

There’s many asking similar questions, but I’m not able to translate the answers to working syntax in my case, can you help me? C#

I’m doing an editor script, and it’s very long, so I’m doing classes in separate files, in other words this is not mono behavior.

In these classes, I am adding to a list with constructor, and this works just fine as a simplified example:


myList.Add(new myConstructorName(“note1”, “note2”, int));


Only problem is the yellow error messages:


myConstructorName must be instantiated using the ScriptableObject.CreateInstance method instead of new myConstructorName


Apparently I cannot get the syntax right, would you be able to type out the syntax I should use from the above?

Thanks a bunch!

It looks like your class myConstructorName inherits from ScriptableObject. All classes of this type must be created using the CreateInstance() method mentioned by your warning. You cannot have a custom constructor. ScriptableObjects are mostly data-storage classes that serialize data like MonoBehaviours, but don’t live on GameObjects. You can fill in the data after instantiation however you like (a custom Init() method, public fields or properties, etc…), but you can’t use the new keyword with a ScriptableObject just like you can’t use it with a MonoBehaviour.

So, in your case, the syntax would look like:






and if you wanted to fill in data immediately:

myList.Add(ScriptableObject.CreateInstance<myConstructorName>().Init("note1", "note2", 3));

Wow @bellicapax !! Wow!! You very, very clever!!

Here’s what: As I’m fiddling with ‘saving’, you are right, I had set “myConstructorName” to be : ScriptableObject - and forgot about it!

So I thought I was trying to fix one problem, but reality was something else… and you… you saw through the whole thing! :smiley:

Respect and thanks!!