利用PrefabEditor监听prefab保存事件

目的

在使用prefab时,可能想要对prefab做一些预处理后再保存,减少运行时的计算量。但美术制作的过程中一般不会有这种考虑。这时就希望有一段程序在prefab保存前做一部分修改,以满足运行时要求。一种解决方案就是利用Unity提供的PrefabStage类。PrefabStage类中提供了prefab打开,关闭,保存时的事件,可注册相应的函数以达到自身的目的。

PrefabStage文档

官方文档地址:https://docs.unity3d.com/ScriptReference/Experimental.SceneManagement.PrefabStage.html
在这里插入图片描述

示例

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

public class Test
{
    [InitializeOnLoadMethod]
    static void RegisterPrefabStageEvents()
    {
        PrefabEditor t = new PrefabEditor();

        PrefabStage.prefabSaving += t.OnSaving;
        PrefabStage.prefabSaved += t.OnSaved;
        PrefabStage.prefabStageClosing += t.OnClosing;
        PrefabStage.prefabStageOpened += t.OnOpend;
    }

    void OnSaving(GameObject go)
    {
        Debug.LogFormat("GameObject({0}) is saving.", go.name);
    }

    void OnSaved(GameObject go)
    {
        Debug.LogFormat("GameObject({0}) is saved.", go.name);
    }

    void OnOpend(PrefabStage stage)
    {
        Debug.LogFormat("GameObject({0}) is opend.", stage.assetPath);
    }

    void OnClosing(PrefabStage stage)
    {
        Debug.LogFormat("GameObject({0}) is closing.", stage.assetPath);
    }
}

当打开prefab场景编辑的时候,Unity编辑器自身会生成PrefabStage实例,该实例中存储有资源名,资源路径等数据,可根据这些内容决定OnSaving和OnSaved中该执行的逻辑。

注意

官方文档显示这个API还处于试验阶段,目前参考的时2020.3版本,其他版本以官方文档或者自身实测结果为准。

参考资料

[1] https://docs.unity3d.com/ScriptReference/Experimental.SceneManagement.PrefabStage.html
[2] https://zhuanlan.zhihu.com/p/148934021

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值