- Home /
Add a ScriptableObject to my Unit Test from inspector
Hi! I have a part in my code with a lot of mathematical calculations. The used equations are ScriptableObjects and I'd like to test the calculations with the same scripted objects. Is there a way to do that? I am aware that I can just use
ScriptableObject.CreateInstance<>()
to create a new object of the type and give it the same values. However, that does invite errors and every time I change a value for one of the equations, I'd have to go through all the tests (or just one if I create a static method to return an object with needed values) to adjust the values, too.
Is there a way to use the objects that I created already within my testclass? Maybe similar to how I just drag/drop them via the Inspector while editing a scene?
If that is not possible, what would be the best alternative? Remove the (ScriptableObject-) equation-objects and create static methods to retrieve objects with the same values within my tests and other MonoBehavior-classes within my scenes?
I hope my issue is understandable, any help is appreciated.
Answer by Hellium · Mar 23 at 05:21 PM
You can load your scriptable object from code
https://docs.unity3d.com/ScriptReference/AssetDatabase.FindAssets.html
CODE NOT TESTED
private ScriptableObjectType LoadScriptableObject()
{
string scriptableObjectName = "ScriptableObjectName";
string[] guids = AssetDatabase.FindAssets($"t:{nameof(ScriptableObjectType)} {scriptableObjectName }");
if(guids.Length == 0)
Assert.Fail($"No {nameof(ScriptableObjectType)} found named {scriptableObjectName}");
if(guids.Length > 0)
Debug.LogWarning($"More than one {nameof(ScriptableObjectType)} found named {scriptableObjectName}, taking first one");
return (ScriptableObjectType) AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guids[0]), typeof(ScriptableObjectType));
}
Thank you so much! I only found solutions that needed the objects to be moved to a Resources folder which I didn't wanna use so this really helped so much! I added the path to the folder the objects are located in to (maybe?) increase preformance and be sure the correct object is picked.
If you already know the path of the object, then yes, you can skip the whole FindAssets
method, and just call return (ScriptableObjectType) AssetDatabase.LoadAssetAtPath(assetPath, typeof(ScriptableObjectType));
. Just keep in mind that moving the Scriptable Object will break your tests.
Your answer

Follow this Question
Related Questions
NUnit and VisualStudio 2 Answers
Reasons to not use playmode unit tests? 0 Answers
NUnit delayed constraint does not appear to work in playmode test 0 Answers
Silence Debug.Log for unit test? 2 Answers
Testing editor scripting 1 Answer