Why "the associated script can not be loaded" for some Scriptable Objects?

I created several scriptable objects that I use in a finite-state-machine. They all work fine except about every 4th or 5th “play” (or whenever I close and reopen my project) the same 3 scriptable objects are no longer valid. Their “script” slot is populated with “None (Mono Script)”, and the warning underneath reads, “The associated script can not be loaded. Please fix any compile errors and assign a valid script.” As a result, I have to recreate these 3 objects periodically. They compile fine, and–aside from their names–are identical to a few other scriptable objects in my solution that work fine and never disappear. So, I’m confused. Anybody know what would cause this, so I can stop recreating these 3 objects every 4-5 test runs of my game? Thanks!

Here’s a screenshot of the error:

Here’s the code of one of the 3 scriptable objects:

It’s hard to tell what could be the reason, however common problems are:

  • your scriptable object is not located in it’s own script file but placed in a file with multiple other classes
  • the name of the script file does not match the actual class name.

Your project looks quite organised so i would doubt the first point. So most likely the file name doesn’t match the class name. Note by “file name” i mean the script file (*.cs) not your scriptable object asset file.

ps: If you have many classes you may want to start using namespaces. Unity does support namespaces for quite some time now.

Also next time it would be better to include code samples as text and mark it as code instead of posting images. It just makes it more difficult for us to read and refer to your code.

Show console errors please

The error is “NullReferenceException: Object reference not set to an instance of an object
State.DoEnterActions (.StateController controller) (at Assets/PluggableAI/Scripts/State.cs:20)”. It’s because the reference to the script behind the scriptable object has been broken, which means the “Decision” element in my State object is “None (Decision)” instead of “Distribute Cards to Opponent 3” as it should be (see screenshot). So, Unity doesn’t think there’s an object. I have to recreate the object, then drag it back into the “Decision” element box in my state in the Inspector. I have to repeatedly do this every time the scriptable object gets removed (as shown in my original screenshot above). Hopefully that makes sense.

I’ve also included a screenshot of the line of code that throws the error, because it’s loaded a null value into my “Actions” array, so it can’t read it at line 20. But that’s not the root-problem. That line of code works once I’ve recreated my scriptable object. My question is why does my scriptable object keep resetting to “None (Mono Script)” every few runs of my program, causing all these problems until I recreate it?!