ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

利用PrefabEditor监听prefab保存事件

2022-01-16 16:03:16  阅读:327  来源: 互联网

标签:prefab GameObject void PrefabEditor PrefabStage go using 监听


目的

在使用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

标签:prefab,GameObject,void,PrefabEditor,PrefabStage,go,using,监听
来源: https://blog.csdn.net/whr12/article/details/122523835

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有