- Home /
how suppress must be instantiated using the ScriptableObject.CreateInstance method warning?
In my project I am using:
System.Activator:CreateInstance(Type)
Which throws the following error:
MyClass must be instantiated using the ScriptableObject.CreateInstance method instead of new MyClass.
This there a way to disable this wrong or a way around it from being called while still using System.Activator.
Answer by Bunny83 · Nov 16, 2017 at 11:47 AM
You don't want to suppress this error but don't use the Activator. ScriptableObjects (just like MonoBehaviours) must not be created with the constructor. They have a native code counterpart like all UnityEngine.Object derived types. When you create it with new this counter part is missing. That means serialization doesn't work properly and the instance will become a fake null instance.
As the error said:
MyClass must be instantiated using the ScriptableObject.CreateInstance method
If you want to use reflection to create your instances you have two options:
Do not derive your class from ScriptableObject and use "normal" classes.
If you want to use ScriptableObjects you can simply do a type check before using the Activator. If the type is derived from ScriptableObject (
typeof(ScriptableObject).IsAssignableFrom(yourType)
) you simply use ScriptableObject.CreateInstance instead of the Activator.
Note: $$anonymous$$eep in $$anonymous$$d that ScriptableObjects (as well as any other UnityEngine.Object) type need to be explicitly destroyed using "Destroy" at runtime or "DestroyImmediate" at edit time. All UnityEngine.Object derived types are "tracked" types in the engine core. They can be found again by using FindObjectOfType / FindObjectsOfType. So those objects are not automatically garbage collected.
Again, if this is unwanted behaviour, don't derive your type from ScriptableObject.
Thanks for the input I should have answer my own question long ago. This ended up being my solution:
var weapons = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.Namespace == "Item.Weapons")
.ToList();
weapons.Remove(typeof(Weapons));
for (var i = 0; i < weapons.Count; i++)
{
var g = ScriptableObject.CreateInstance(weapons[i]);
((Weapons)g).Init();
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612095108im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Servers connection differences/uses 1 Answer
Type in bug in editor 1 Answer
Determine if game object is tyoepf One Prefab 3 Answers
Unity4, resolution-independent typography 1 Answer
Array of Transform[] not correctly typed in Javascript 1 Answer