Use CreateInstance to create a scriptable object

Rule ND3204 API Usage / Unity

Instances of types deriving from UnityEngine.ScriptableObject must be created via ScriptableObject.CreateInstance<T>(): the Unity engine needs to create the object itself to handle Unity message methods.

How to fix

Replace new Foo() expressions with ScriptableObject.CreateInstance<Foo>() expressions.

CQLinq source

This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.

// <Name>Use CreateInstance to create a scriptable object</Name>
// <Id>ND3204:UseCreateInstanceToCreateAScriptableObject</Id>

warnif count > 0 
let scriptableObjects = Types.Where(t => t.DeriveFrom("UnityEngine.ScriptableObject".AllowNoMatch()))
let ctors = scriptableObjects.SelectMany(t => t.Constructors).ToHashSetEx()

from m in Application.Methods.ThatCreateAny(scriptableObjects)
let ctorsCalled = m.MethodsCalled.Intersect(ctors).ToArray()
let typesInstantiated = ctorsCalled.ParentTypes()
where typesInstantiated.Any()
select new { 
  m,
  shouldntInstantiate = typesInstantiated,
  Debt = (5 + 5*typesInstantiated.Count()).ToMinutes().ToDebt(),
  Severity = Severity.Medium
}

//<Expl>
// The *{0}* shouldn't instantiate directly the *{1}*
// and should use the method *ScriptableObject.CreateInstance<T>()* instead.
//</Expl>

//<Desc>
// Instances of types deriving from *UnityEngine.ScriptableObject* must be
// created via *ScriptableObject.CreateInstance<T>()*: the Unity engine
// needs to create the object itself to handle Unity message methods.
//</Desc>

//<HowToFix>
// Replace *new Foo()* expressions with
// *ScriptableObject.CreateInstance<Foo>()* expressions.
//</HowToFix>

API Usage / Unity: all 9 items