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
- UI Toolkit throws warning and fails to clear references when fields are not typed as UnityEngine.Object
- "Shader warning in 'Hidden/Light2D': implicit truncation of vector type" is thrown when building Universal 2D template
- AI Assistant breaks compilation of packages using System.Runtime.CompilerServices.Unsafe via auto-referencing
- Unity Hub checks the "Documentation" module by default on the 6.4 and 6.5 streams despite that it was unchecked with the previous installs
- Shortcut that toggles between Dopesheet and Curves Views in the Animation Window's Timeline is mislabed
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.
```