SerializeField only on some target platforms

Hello !

I would like to serialize a field only on some platforms and/or only on editor.

For example, let’s assume I have a MonoBehaviour, that should have a reference to some ScriptableObject only on Editor OR on Standalone (Win, Mac, OSX) builds :

public class SomeComponent : MonoBehaviour
{
#if UNITY_EDITOR || UNITY_STANDALONE
    [SerializeField]
    public SomeScriptableObjectType _someScriptableObject;
#endif
}

Will the above code compile correctly on every platform, in particular for the platforms where I don’t want to this ScriptableObject to be referenced and included in the build (e.g. Android, iOS…) ?

I remember that this kind of serialization depending on #define might cause errors like “different serialization layout”, but I cannot find precise info about it in the documentation.
It seems it is now supported, at least for serialization depending on editor or runtime :
https://docs.unity3d.com/2021.3/Documentation/Manual/script-Serialization.html#:~:text=: MonoBehaviour {-,#if UNITY_EDITOR,-public int m_intEditorOnly

If Unity cannot support conditional field serialization, for this use case, I will probably build and load an AssetBundle depending on the platform. But that seems a little overkill.

Pretty sure on more recent Unity versions this is fine to do.

Though the best solution is to, of course, test.

1 Like

Just did a test in the last hour, and it looks like it’s working fine indeed ! (Unity 2021.3)

Is that ScriptableObject so heavy that it must not exist in, let’s say a mobile build?

If it contains a list of textures that you won’t reference elsewhere, then it would make sense to ensure the ScriptableObject and its textures are not referenced. If it’s just “values” then … don’t worry about a couple bytes.

I would nevertheless try to implement it using a custom build step instead before resorting to #if serialized fields. Unity allows you to hook into the build process and by doing so, you could simply get all SomeComponent instances and set the reference to null. Provided you ensure this only gets saved into the build of course, either by saving it to build-only scenes or restoring everything after the build (there may be other options if you think about it).