有时候会在场景中修改大量的prefab的实例物体,然后又需要同步到prefab上,这个脚本就非常有用了:
using UnityEngine;
using UnityEditor;
public class EditorHelp
{
[MenuItem("Tools/自动保存修改到Prefab", false, 0)]
static void AutoSaveGameObjectToPrefab()
{
GameObject[] selections = Selection.gameObjects;
foreach (GameObject select in selections)//遍历每个选中的物体
{
//获取prefab路径
string prefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(select);
Debug.Log(prefabPath);
//如果资源不对则不继续执行
if (prefabPath.EndsWith(".prefab") == false) continue;
//因为prefab保存无法保存最父物体的Position和rotation
//不知道Unity怎么考虑的,就是直接点场景中的apply也无法保存root物体的位置和角度,但是大小又可以
//因此我们这里自己进行一下值获取和赋值
GameObject prefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
prefab.transform.localPosition = select.transform.localPosition;
prefab.transform.rotation = select.transform.rotation;
//保存修改
bool isSuccess = false;
PrefabUtility.SaveAsPrefabAsset(select, prefabPath, out isSuccess);
Debug.Log("修改" + prefabPath + ":" + isSuccess);
}
AssetDatabase.Refresh();
}
}
网友评论