使用 ViewData API 可在域重新加载后或 Editor 重新启动时保留特定于 UI 的状态数据。持久数据存储在每个 EditorWindow
上。每个 VisualElement
都有一个 persistenceKey
,必须设置它才能启用 ViewData
持久性。
本主题举例说明如何为已实现的控件和新对象启用 ViewData 持久性。
如果一个元素已经支持持久性,请设置 persistenceKey
来告诉系统其需要保存数据。与其他视觉元素的键相比,persistenceKey
必须是唯一的。
创建新的 VisualElement
时可使其支持持久数据。第一步是将持久数据封装在元素类中的一个或多个 Serializable
类中:
[Serializable]
public class ExtraData
{
public int m_Value = 0;
}
public ExtraData m_ExtraData;
第二步是每当持久数据发生变化时调用 SavePersistentData()
方法。这样可确保正确保存数据:
public int value
{
get { return m_Value; }
set
{
// 执行操作
SavePersistentData();
}
}
最后一步是覆盖 OnPersistentDataReady()
:
// 一旦我们知道可以访问持久数据存储,我们就在此处
// 开始真正的初步工作。
protected override void OnPersistentDataReady()
{
base.OnPersistentDataReady();
//(可选)根据当前父项获取更具唯一性的键。
//这包括我们自己的 `persistenceKey`。
var key = GetFullHierarchicalPersistenceKey();
//获取或创建新的 ExtraData 对象。
m_ExtraData = GetOrCreatePersistentData<ExtraData>(m_ExtraData, key);
}
上面的示例还演示了如何生成和分配唯一键。一旦指定了键,GetOrCreatePersistentData()
就会返回具有持久性状态的对象,或者按原样返回。
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.