【问题标题】:How to assign programmatically an Interactable Event in MRTK如何在 MRTK 中以编程方式分配可交互事件
【发布时间】:2021-12-20 02:02:34
【问题描述】:

我正在 Unity3D 中创建要在 Hololens 2 中显示的地图。我正在使用 MRTK 编写可交互功能的代码。

由于地图包含许多独立的国家/地区,其回复onClick 可能会随时间而变化,因此我决定以编程方式添加所需的组件。例如:

public Transform worlmap;
public Microsoft.MixedReality.Toolkit.UI.Theme mTheme;
public Microsoft.MixedReality.Toolkit.UI.States mStates;
List<Microsoft.MixedReality.Toolkit.UI.Theme> themes;


    void Start()
{
    themes = new List<Microsoft.MixedReality.Toolkit.UI.Theme>();
    if (mTheme)
    {
        themes.Add(mTheme);
    }

    // Looping through all the countries in worldMap
    foreach (Transform country in worldMap)
    {
        // Adding the 4 components which make a GameObject interactable in Hololens
        country.gameObject.AddComponent<Microsoft.MixedReality.Toolkit.UI.Interactable>();
        country.gameObject.AddComponent<Microsoft.MixedReality.Toolkit.UI.PressableButton>();
        country.gameObject.AddComponent<Microsoft.MixedReality.Toolkit.Input.NearInteractionTouchable>();
        country.gameObject.AddComponent<MeshCollider>();

        // Assigning State
        country.gameObject.GetComponent<Microsoft.MixedReality.Toolkit.UI.Interactable>().States = mStates;
        
        // Assigning the Profiles (Will definine the colors based on the State)
        Microsoft.MixedReality.Toolkit.UI.InteractableProfileItem mProfile = new Microsoft.MixedReality.Toolkit.UI.InteractableProfileItem();
        mProfile.Themes = themes;
        mProfile.Target = country.gameObject;
        country.gameObject.GetComponent<Microsoft.MixedReality.Toolkit.UI.Interactable>().Profiles.Add(mProfile);
        
        // Assigning Events
        // TODO
    }
}

下面的部分正在运行,但我无法将事件分配给同一循环中的不同国家/地区。

我可以在编辑器中定义这些事件,例如:

但由于它是一个重复性活动,可能会随着时间的推移而略有变化,因此我试图在上述脚本的循环内以编程方式实现相同的操作。

这是我尝试过的,但它不起作用:

// Creating an Event
Microsoft.MixedReality.Toolkit.UI.InteractableEvent mEvent = new Microsoft.MixedReality.Toolkit.UI.InteractableEvent();

// Assigning the method to be executed during onClick
mEvent.Event.AddListener(country.gameObject.GetComponent<CountrySelected>().printName)

// Assigning the Event to Interactable 
country.gameObject.GetComponent<Microsoft.MixedReality.Toolkit.UI.Interactable>().InteractableEvents.Add(mEvent);

以编程方式将事件添加到 MRTK 中的可交互对象的正确方法是什么?

【问题讨论】:

    标签: c# unity3d hololens mrtk


    【解决方案1】:

    要在运行时为 Interactable 组件分配 OnClick 事件,请尝试以下代码:

        this.GetComponent<Interactable>().OnClick.AddListener(MyFun1);
    

    Unity 编辑器中的 Interactable 组件配置文件可能不会在运行时显示新方法,但它确实在场景中工作。

    【讨论】:

    • 谢谢,完美运行
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 2021-08-31
    • 2012-08-04
    相关资源
    最近更新 更多