要在 Unity 从模板实例化新场景时运行自定义代码,请创建一个场景模板管线脚本并将其连接到模板。每次从该模板创建新场景时,Unity 也会创建管线脚本的新实例。
要将脚本连接到模板:
您还可以使用 SceneTemplateAsset.templatePipeline
方法通过 C# 将脚本连接到模板。
场景模板管线脚本必须派生自 [ISceneTemplatePipeline
] 接口或 [SceneTemplatePipelineAdapter
]。它应该实现您要响应的事件;例如,下面代码中的 BeforeTemplateInstantiation
或 AfterTemplateInstantiation
。
示例:
using UnityEditor.SceneTemplate;
using UnityEngine;
using UnityEngine.SceneManagement;
public class DummySceneTemplatePipeline : ISceneTemplatePipeline
{
public void BeforeTemplateInstantiation(SceneTemplateAsset sceneTemplateAsset, bool isAdditive, string sceneName)
{
if (sceneTemplateAsset)
{
Debug.Log($"Before Template Pipeline {sceneTemplateAsset.name} isAdditive: {isAdditive} sceneName: {sceneName}");
}
}
public void AfterTemplateInstantiation(SceneTemplateAsset sceneTemplateAsset, Scene scene, bool isAdditive, string sceneName)
{
if (sceneTemplateAsset)
{
Debug.Log($"After Template Pipeline {sceneTemplateAsset.name} scene: {scene} isAdditive: {isAdditive} sceneName: {sceneName}");
}
}
}
当您从具有可克隆依赖项的模板创建新场景时,Unity 会执行多个文件操作。大多数这些操作会触发 Unity 事件,您可以在脚本中监听这些事件并进行响应。
实例化顺序如下:
Unity 触发模板资源的 ISceneTemplatePipeline.BeforeTemplateInstantiation
事件,并将该资源绑定到它触发的 ISceneTemplatePipeline
脚本。
Unity 触发 SceneTemplate.NewTemplateInstantiating
事件。
Unity 创建一个新场景,它是模板场景的副本。
Unity 创建一个与新场景同名的文件夹,并将所有可克隆的依赖项复制到该文件夹中。
Unity 重新映射对所有可克隆资源的引用,使得新场景指向克隆资源。
Unity 触发模板资源的 ISceneTemplatePipeline.AfterTemplateInstantiation
,并将该资源绑定到它触发的 ISceneTemplatePipeline
脚本。
Unity 触发 SceneTemplate.NewTemplateInstantiated
事件。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.