Search Issue Tracker
Won't Fix
Votes
0
Found in
2019.4
2020.3
2021.2
2022.1
2022.1.0b9
2022.2
Issue ID
1406808
Regression
No
PrefabUtility.SaveAsPrefabAsset() return null when called inside methods with [DidReloadScripts] callback
How to reproduce:
1. Open the user's attached project
2. In the Project window, navigate to Assets/Test
3. Delete the "check" Prefab
4. Open TestSavePrefab.cs
5. Add a comment line to trigger recompilation
6. Return to the Editor and observe the Console
Expected result: "Success: check" is logged to the console
Actual result: "Saved prefab is null: check" is logged to the Console
Reproducible with: 2019.4.37f1, 2020.3.32f1, 2021.2.17f1, 2022.1.0b14, 2022.2.0a9
Add comment
All about bugs
View bugs we have successfully reproduced, and vote for the bugs you want to see fixed most urgently.
Latest issues
- Articulation Body with 'Revolute' Joint Type has erratic behavior when Upper Limit is set to above 360
- WebGL Player fails to render Scene when Terrain with Detail Mesh is added and WebGPU Graphics API is used
- Inconsistent errors are logged when different types are passed into the Query "Q<>" method in UIToolkit and the ancestor VisualElement is null
- Crash on GetMaterialPropertyByIndex when opening a specific Scene
- Discrepancies in the styling are present when using a TSS file instead of a USS file in custom EditorWindow
Resolution Note:
`DidReloadScripts` callbacks are called during AssetDatabase refresh. All actions from these callbacks that trigger AssetDatabase refresh will fail or partially fail. `PrefabUtility.SaveAsPrefabAsset` saves the Prefab on disk and triggers AssetDatabase refresh to import the newly saved Prefab in order to return a reference to its Root GameObject. This operation fails by design and it returns null, even if the Prefab asset is saved correctly.
To check if the save was successful one can use https://docs.unity3d.com/ScriptReference/PrefabUtility.SaveAsPrefabAsset.html
In the documentation it states:
```
The returned object is the root GameObject of the saved Prefab Asset, if available. If the editor in currently in the middle of an asset editing batch operation, as controlled with AssetDatabase.StartAssetEditing and AssetDatabase.StopAssetEditing, assets are not immediately imported upon being saved. In this case, SaveAsPrefabAsset will return null even if the save was successful because the saved Prefab Asset was not yet reimported and thus not yet available.
```