保存预制,很简单的功能,但是走了弯路,记录一下吧
private void SavePrefab(Transform root) { PrefabInstanceStatus status = PrefabUtility.GetPrefabInstanceStatus(Root.gameObject); if (status == PrefabInstanceStatus.NotAPrefab) { // 如果不是预制件,创建一个新的预制件 string path = EditorUtility.SaveFilePanel("Save prefab", "Assets/", Root.name + ".prefab", "prefab"); if (path.Length != 0) { bool suc; PrefabUtility.SaveAsPrefabAssetAndConnect(Root.gameObject, path, InteractionMode.UserAction, out suc); Debug.Log("suc =" + suc); } } else { string prefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(Root.gameObject); Debug.Log($"{prefabPath}"); PrefabUtility.SaveAsPrefabAssetAndConnect(Root.gameObject, prefabPath, InteractionMode.UserAction); //Debug.Log("suc="+ suc); } }
如果要保存的Gameobject 本身就是一个预制,不能用下方方法
PrefabUtility.SavePrefabAsset(GameObject root) 这个不是实例才生效,否则报错:
ArgumentException: Can't save a Prefab instance
报错的原因:只要物体拖到场景里,就是一个实例了,所以这个只能用不是实例的物体才可以用