Object references are not restored when .meta files are restored (possible bug)

Hi!
I am working on a Unity plugin that uses several types of ScriptableAssets I have created. Each of these assets are automatically generated based on user inputs (rather than manually via the “Create” menu).

These generated assets are referenced in by objects in the scene, as so:
9757173--1397178--upload_2024-4-8_15-40-58.png

When the user changes certain preferences, the assets need to be rebuilt. Normally, this would cause the references to the assets to be lost (because we are destroying them and then recreating them).

In order to preserve these references, we first copy the old .meta files into the application’s temp folder, then delete and recreate the assets, then replace the new meta files with the old ones.

However, the references remain broken:
9757173--1397181--upload_2024-4-8_15-44-50.png

I have checked the .meta files and the scene files after the whole process, and the GUID that the scene uses for each asset corresponds to the one in its .meta file.

However, if I then save the scene, then close and reopen Unity, the references are ok again. This also works by simply loading another scene and returning to this one.
However, selecting a different object in the scene or running the game do not fix the issue (the game will throw nullreference errors when accessing one of the objects).

Is there a way I can force Unity to “refresh” these references in some way, directly from a script?

Ouch! :face_with_spiral_eyes:

This is at least awkward, if not potentially brittle. More so if you intend this tool for a team or even customers.

It probably isn’t working for you because you use System.IO to move the files, and afterwards you didn’t call ImportAsset for every .meta file. Is that right?
And when you add ImportAsset for every asset you may notice that it is slow. I mean beyond how slow creating assets is to begin with. So you’ll also need to enclose the process in Start/StopAssetEditing and properly enclose those in try/finally.

But really … why do you blindly recreate all assets in the first place? You really only need to update their values, if at all. Only create assets that are new, and delete assets that are gone. If your process can’t handle this, fix it. Because that’s the only way to properly write such a tool. It’ll perform better as a result.

1 Like