How to stop Preset loadings from nuking references?

Many of my scripts have assigned references to objects in them, and values.

The values I want to save to Presets, and then reload different variances during Play Mode.

But doing so nukes the references to objects… even if they’re left public, but hidden from the Inspector.

Is there a way around this problem?

You mean editor presets: https://docs.unity3d.com/ScriptReference/Presets.Preset.html ?

Those are an editor only construct and can’t be built into a project (unless you’re using this for testing purposes).

In any case in the link you can under ‘Applying Partial Presets’ you can see how to do what you’re looking for.

1 Like

I’m using 2019.LTS, which doesn’t seem to have this partial presets feature, so will probably have to try harder to find a way to prevent serialisation (to stop the Presets overriding references to null), and/or remove those properties from the scripts that are afflicted by this corruption from Preset loading.

This is not so much for testing purposes as it is for creative exploration, yes, in editor. I’m using them as presets. Which I thought might be fraught with problems as I’ve not seen others doing it. But it seemed like a good idea at the time… rather than using forcibly creating lots of prefabs during Play mode creative exploration, as “presets”. Am beginning to rethink that.

POSSIBLE SOLUTION - Workaround:

for anyone coming to this later, and learning that Presets usage nullifies many object references… if you can rebuild those references inside your script being subjected to this “cleansing” by the Preset usage, do so with the

OnValidate()

call that comes as a result of the usage of the new Preset to check which references are lost (null) and then rebuild them by re-getting them.

eg:

void OnValidate ( ) {

        if ( myReferencedObject == null ) {
            myReferencedObject = GetComponent< TheObjectWanted >( );
        }

Performance concerns begone…

Because Presets are an editor only feature, and OnValidate() is an editor only call, the null check and gaining/restoring of references via Get/Find etc, often considered costly, are not done in builds, only in the editor when you load Presets.