在工作中出现预制体跟场景中的物体关联缺失的问题。为了方便写了个小工具。
——————————————————————————————————————
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
[ExecuteInEditMode]
public class InsPrefabToScrene : EditorWindow
{
[MenuItem("工具箱/预制体替换")]
static void AddWindown()
{
Rect rect = new Rect(0,0,500,500);
InsPrefabToScrene window = (InsPrefabToScrene)GetWindow(typeof(InsPrefabToScrene), false, "预制体替换");
window.Show();
}
[SerializeField]
public GameObject obj;
[SerializeField]
public List<GameObject> list;
private SerializedObject serHelp;
private SerializedProperty serobj;
private SerializedProperty serPty;
private void OnEnable()
{
serHelp = new SerializedObject(this);
serPty = serHelp.FindProperty("list");
serobj = serHelp.FindProperty("obj");
}
private void OnGUI()
{
serHelp.Update();
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(serobj, new GUIContent("预制体"), true);
EditorGUILayout.PropertyField(serPty,new GUIContent("需要替换的物体"), true);
if (GUILayout.Button("替换"))
{
替换();
}
if (EditorGUI.EndChangeCheck())
{//提交修改
serHelp.ApplyModifiedProperties();
serPty = serHelp.FindProperty("list");
serobj = serHelp.FindProperty("obj");
}
}
void 替换()
{
if (obj == null)
{
Debug.Log("预制体为空");
}
if (list==null|| list.Count==0)
{
Debug.Log("列表数量小于0");
}
for (int i = 0; i < list.Count; i++)
{
GameObject game = PrefabUtility.InstantiatePrefab(obj)as GameObject;//Instantiate(obj) as GameObject;//
game.transform.SetParent(list[i].transform.parent);
game.transform.position = list[i].transform.position;
game.transform.rotation = list[i].transform.rotation;
game.transform.localScale = list[i].transform.localScale;
GameObject gameObject = list[i];
// PrefabUtility.SaveAsPrefabAssetAndConnect(gameObject, PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(obj), InteractionMode.AutomatedAction);
DestroyImmediate(gameObject);
}
list.Clear();
}
}