Using Source Generators to create MonoBehaviours/ScriptableObjects

Hello!

I’m currently dealing with a bit of boilerplate code, and as I’ve played around with Roslyn’s source generators, I thought it would be worth a try.

Basically, I have a generic abstract class Generic inheriting ScriptableObject that I would like to have in multiple flavours, e.g. GenericGameObject inheriting Generic without having to write the class declarations and other tags such as [CreateAssetMenu] again and again. The code works fine for POCOs, but UnityEngine.Objects such as ScriptableObjects (and likely MonoBehaviours) are not working. They can be created, but are lost upon restarting the editor - likely because they don’t have a meta file associated with them and only really exist in the compiled assembly.

So my question would be: Is it possible (or planned) that source generators can create ScriptableObjects/MonoBehaviours that are recognized by the editor?

Are you making sure to generate mono script asset for them? Unity - Scripting API: MonoScript

The usual restrictions apply. You can only have one monobehaviour per monoscript asset.

I’m not working with assets at all because I’m using source generators (Unity - Manual: Roslyn analyzers and source generators) which are outside of the Unity editor (or rather, inside the compiler), so I suppose from Unity’s PoV, the types just show up in the compiled assembly (with no prior reference to a script or similar). For testing purposes, I put each type into an own “file”, albeit I think it’s more of a suggestion at that point rather than a real file.

I’ve also tried to put the generator into an semi-empty .asmdef in the hope that by adding it to a intermediary assembly it would get picked up - but sadly that does not appear to be the case. The ScriptableObjects/MonoBehaviours that are generated this way.

Reading up on MonoScripts makes me wonder though, if it’s one MB per asset, how does Unity deal with pre-compiled assemblies that contain multiple MBs/SOs?

I’ve also encountered the same issue. Have you managed to resolve it yet?

I dont think there is a current solution, nor this will be supported in the near future

Unity Issue Tracker - Scriptable Objects do not get created when generating from Source Generators

Today we only support this kind of behavior when the cs file are imported.
The reason is that is how we deterministically track its ID, the ID are part of the *.cs.meta file.
Hopefully we can solve this at a later time, but currently this is sadly not something we can handle.