Version: 6000.3
语言: 中文
添加设备
“层次结构”窗口

扩展设备模拟器

设备模拟器支持插件来扩展其功能,并在模拟器视图中更改控制面板的UI。

创建插件

要创建设备模拟器插件,请扩展 DeviceSimulatorPlugin 类。

要将 UI 插入到设备模拟器视图中,您的插件必须:

  • 覆盖title属性返回非空字符串。
  • 覆盖OnCreateUI方法返回包含 UI 的 VisualElement

如果您的插件不满足这些条件,设备模拟器会实例化插件,但不会在模拟器视图中显示其 UI。

以下示例演示了如何创建一个插件,该插件会覆盖 title 属性并将 UI 添加到模拟器视图。

public class TouchInfoPlugin : DeviceSimulatorPlugin
{
    public override string title => "Touch Info";
    private Label m_TouchCountLabel;
    private Label m_LastTouchEvent;
    private Button m_ResetCountButton;

    [SerializeField]
    private int m_TouchCount = 0;

    public override void OnCreate()
    {
        deviceSimulator.touchScreenInput += touchEvent =>
        {
            m_TouchCount += 1;
            UpdateTouchCounterText();
            m_LastTouchEvent.text = $"Last touch event: {touchEvent.phase.ToString()}";
        };
    }

    public override VisualElement OnCreateUI()
    {
        VisualElement root = new VisualElement();
        
        m_LastTouchEvent = new Label("Last touch event: None");
        
        m_TouchCountLabel = new Label();
        UpdateTouchCounterText();

        m_ResetCountButton = new Button {text = "Reset Count" };
        m_ResetCountButton.clicked += () =>
        {
            m_TouchCount = 0;
            UpdateTouchCounterText();
        };

        root.Add(m_LastTouchEvent);
        root.Add(m_TouchCountLabel);
        root.Add(m_ResetCountButton);
            
        return root;
    }

    private void UpdateTouchCounterText()
    {
        if (m_TouchCount > 0)
            m_TouchCountLabel.text = $"Touches recorded: {m_TouchCount}";
        else
            m_TouchCountLabel.text = "No taps recorded";
    }
}
添加设备
“层次结构”窗口