- Home /
Modify prefabs in editor script
I am trying to write a script that will update the material settings on a set of prefabs, which I can then save.
I have seen a number of questions asking to do this, but none of the examples work. My code is below.
Whenever I run this, the editor reacts by re-importing assets, and there are no exceptions indicating that my call to ReplacePrefab() is incorrect - but the prefabs themselves remains unchanged.
What have I missed?
AssetDatabase.StartAssetEditing();
var guids = AssetDatabase.FindAssets(" t:GameObject",new string[]{"Assets/city_assets"});
foreach(var g in guids)
{
string path = AssetDatabase.GUIDToAssetPath(g);
GameObject prefab = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
GameObject instance = Object.Instantiate(prefab);
UpdateMaterials(instance); //operates on the components of instance
PrefabUtility.ReplacePrefab(instance, prefab, ReplacePrefabOptions.ConnectToPrefab);
}
AssetDatabase.StopAssetEditing();
I dont think Object.Instantiate should work here. This instantiates a object in the scene, as far asI know it does not create an asset.
I guess you'll need PrefabUtility.CreatePrefab or just modify the prefab itself ins$$anonymous$$d of creating a copy, modifying that and replacing it...
What happens if you do something like this?
AssetDatabase.StartAssetEditing(); // Not sure if needed
var guids = AssetDatabase.FindAssets(" t:GameObject",new string[]{"Assets/city_assets"});
foreach(var g in guids)
{
string path = AssetDatabase.GUIDToAssetPath(g);
GameObject prefab = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
Update$$anonymous$$aterials(prefab);
}
AssetDatabase.StopAssetEditing(); // Not sure if needed
ps. Note that it could be that the problem lies with editing the material. As $$anonymous$$aterials of prefabs are assets themself. So if you modify renderer.material ins$$anonymous$$d of renderer.sharedmaterial your change to the material will most likely not persist and cause materials to 'leak' (you should get an info log in the console when that happens I believe).
@troien I thought that would work also - it was the first thing I tried. Unfortunately the same thing happens - no changes take effect, even when flagging the object as dirty. I will investigate further and see if it is a problem with the materials settings.
Answer by nark · Oct 13, 2016 at 07:00 AM
try PrefabUtility.InstantiatePrefab instead of Object.Instantiate, and call AssetDatabase.SaveAssets() after you finish all the work
Your answer
Follow this Question
Related Questions
How to keep reference linked when replace prefab through editor scripts? 1 Answer
Add Asset Bundle Name to a prefab in "Editor Code" 1 Answer
How do I change the name of the prefab in the prefab folder with code? 0 Answers
Code-generated changes to prefab override properties not persisting 0 Answers