包含此页的版本:
不含此页的版本:
版本: 2023.2+
此示例演示如何在自定义控件中使用自定义 USS 变量。
此示例创建一个自定义控件,该控件从 USS 读取两种颜色,并使用它们生成纹理。
您可以在此 GitHub 存储库中找到此示例创建的已完成文件。
本指南适用于熟悉 Unity 编辑器、UI 工具包和 C# 脚本的开发人员。在开始之前,请熟悉以下内容:
创建 C# 脚本来定义自定义控件,并创建 USS 文件来定义自定义样式。
create-custom-style-custom-control以存储您的文件。ExampleElementCustomStyle文件夹中,创建一个名为ExampleElementCustomStyle.cs并将其内容替换为以下内容:using UnityEngine;
using UnityEngine.UIElements;
namespace UIToolkitExamples
{
[UxmlElement]
public partial class ExampleElementCustomStyle : VisualElement
{
// Use CustomStyleProperty<T> to fetch custom style properties from USS
static readonly CustomStyleProperty<Color> S_GradientFrom = new CustomStyleProperty<Color>("--gradient-from");
static readonly CustomStyleProperty<Color> S_GradientTo = new CustomStyleProperty<Color>("--gradient-to");
// Image child element and its texture
Texture2D m_Texture2D;
Image m_Image;
public ExampleElementCustomStyle()
{
// Create an Image and a texture for it. Attach Image to self.
m_Texture2D = new Texture2D(100, 100);
m_Image = new Image();
m_Image.image = m_Texture2D;
Add(m_Image);
RegisterCallback<CustomStyleResolvedEvent>(OnStylesResolved);
}
// When custom styles are known for this control, make a gradient from the colors.
void OnStylesResolved(CustomStyleResolvedEvent evt)
{
Color from, to;
if (evt.customStyle.TryGetValue(S_GradientFrom, out from)
&& evt.customStyle.TryGetValue(S_GradientTo, out to))
{
GenerateGradient(from, to);
}
}
public void GenerateGradient(Color from, Color to)
{
for (int i = 0; i < m_Texture2D.width; ++i)
{
Color color = Color.Lerp(from, to, i / (float)m_Texture2D.width);
for (int j = 0; j < m_Texture2D.height; ++j)
{
m_Texture2D.SetPixel(i, j, color);
}
}
m_Texture2D.Apply();
m_Image.MarkDirtyRepaint();
}
}
}
创建一个名为 USS 文件ExampleElementCustomStyle.uss并将其内容替换为以下内容:
ExampleElementCustomStyle {
--gradient-from: red;
--gradient-to: yellow;
}
创建 UI 文档以使用自定义控件,并将自定义样式应用于自定义控件。
ExampleElementCustomStyle文件夹中,创建一个名为ExampleElementCustomStyle.uxml.ExampleElementCustomStyle.uxml在 UI Builder 中打开它。ExampleElementCustomStyle.uss作为现有 USS 进行备案。这会将自定义 USS 变量应用于正方形。