Can ScriptableObject Properties/Fields be set via code?

Can ScriptableObject Properties/Fields be set via code?

This is the scriptable object class (example)

public class so1 : SerializedScriptableObject
{
    public bool isSquad; // example 1
    public bool isTest {get; set;} // example 2

}

This is the code by which I instantiate the scriptable Object and attempt to set it’s fields/properties after having instantiated it:

SO = ScriptableObject.CreateInstance<so1>();

SO.isSquad = true;
SO.isTest.set(true);
AssetDatabase.CreateAsset(SO, "Assets/NewScripableObject.asset");
AssetDatabase.SaveAssets();

This isn’t working. I get the error: Cannot resolve symbol “isSquad”.
However in the debugger I can see the SO in memory with all the fields/properties, so why can I not set them?

Well that was a slip up on my part, I forgot to declare SO correctly.

so1 SO  = ScriptableObject.CreateInstance<so1>();

This lets me access the fields as expected, just wondering why I wasn’t getting a compile error without this.

How were you doing it before, using new? That will compile but won’t run because you will have only created the C# side of the object and the engine won’t know anything about it, and thus it won’t be save-able.

Using CreateInstance creates the whole nine yards: the C++ native engine side plus the C# side (your fields / code).

1 Like