预制体替换编辑器

在工作中出现预制体跟场景中的物体关联缺失的问题。为了方便写了个小工具。

——————————————————————————————————————

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();
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值