Unity EditorWindow拓展 给prefab上某个字段赋值

  • Post author:
  • Post category:其他


using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class AutoRefreshWindow : EditorWindow
{
    [SerializeField] private List<GameObject> prefabs = new List<GameObject>();
    //序列化对象
    private SerializedObject serializedObject;
    //序列化属性
    private SerializedProperty serializedProperty;
    private string path;

    private void OnEnable()
    {
        //使用当前类初始化
        serializedObject=new SerializedObject(this);
        //获取当前类中可序列话的属性
        serializedProperty = serializedObject.FindProperty("prefabs");
    }

    [MenuItem("Window/AutoRefreshWindow")]
    public static void ShowWindow()
    {
        AutoRefreshWindow window = (AutoRefreshWindow) GetWindow(typeof(AutoRefreshWindow), false, "AutoRefresh", true);
        window.Show();
    }

    private void OnGUI()
    {
       //更新
       serializedObject.Update();
       //开始检查是否有修改
       EditorGUI.BeginChangeCheck();
       
       //显示属性
       //第二个参数必须为true,否则无法显示子节点即List内容
       EditorGUILayout.PropertyField(serializedProperty, true);
       //结束检查是否有修改
       if (EditorGUI.EndChangeCheck())
       {
           //提交修改
           serializedObject.ApplyModifiedProperties();
       }

       //目的:给prefab上的animator赋值
       //直接用prefabs[i]会报错:Can't save persistent object as a Prefab asset
       //改用AssetDatabase.LoadAssetAtPath 实例化一个新的游戏物体后再进行替换可解决
       if (GUILayout.Button("AutoRefreshAnimator"))
       {
           for (int i = 0; i < prefabs.Count; i++)
           {
               path = AssetDatabase.GetAssetPath(prefabs[i]);
               //获取对象的路径
               GameObject newPrefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);
               GameObject instance = (GameObject)PrefabUtility.InstantiatePrefab(newPrefab);
               Animator anim = instance.GetComponent<Animator>();
               instance.GetComponent<Character>().SetAnimator(anim);
               PrefabUtility.SaveAsPrefabAsset(instance, path);
               DestroyImmediate(instance);
           }
           
           Debug.Log("Refresh Animator done!");
       }
    }
}

这段代码的主要功能是给prefab上的animator字段赋值Animator组件,将prefab拖入窗口中即可实现添加引用



版权声明:本文为qq_38327432原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。