订阅活动 Unity VR

Subscribe event Unity VR

Unity 分享不同之处 assets/script 使用 VR。我尝试开发一种简单的体验来提高我对不同 Unity 功能的了解,但我在调用事件时遇到了麻烦。

在脚本 MenuButton.cs 中,您可以订阅 OnButtonSelected 事件,但我不知道如何订阅:

MenuButton.cs

    public class MenuButton : MonoBehaviour
    {
         public event Action<MenuButton> OnButtonSelected;                   // This event is triggered when the selection of the button has finished.
...

         private IEnumerator ActivateButton()
         {
                // If anything is subscribed to the OnButtonSelected event, call it.
                if (OnButtonSelected != null)
                    OnButtonSelected(this);
         }
    }

我尝试了多种不成功的方式来从另一个脚本订阅此事件,例如:

namespace VRStandardAssets.Menu
{
    public class GetDiscover : MonoBehaviour
    {
        [SerializeField] private MenuButton m_MenuButton;         // This controls when the selection is complete.

        void OnEnable()
        {
            m_MenuButton.OnButtonSelected += Teleport;
        }


        void OnDisable()
        {
            m_MenuButton.OnButtonSelected -= Teleport;
        }


        void Teleport()
        {
            Debug.Log("Hello");
        }
    }

}

但我有错误:"error CS0123: A method or delegate VRStandardAssets.Menu.GetDiscover.Teleport()' parameters do not match delegateSystem.Action(VRStandardAssets.Menu.MenuButton)' parameters"。

这是什么意思?我只是在寻找调用事件的最简单方法...

我也尝试使用委托方法,但它也行不通... 也许我不太了解事件系统 Unity 的功能,即使我已经遵循了一些教程,也欢迎一些清晰的解释:

https://unity3d.com/fr/learn/tutorials/topics/scripting/events-creating-simple-messaging-system

https://unity3d.com/fr/learn/tutorials/topics/scripting/events

这个错误的意思是,当您订阅 "OnButtonSelected" 事件时,您定位的方法(在您的情况下,"Teleport")必须接受类型为 VRStandardAssets.Menu.MenuButton 的参数.

这就是事件系统告诉听众选择了哪个按钮的方式。

所以,你可以使用这样的东西:

void Teleport(VRStandardAssets.Menu.MenuButton buttonPressed)
{
    // if you care which button, access buttonPressed parameter here..
    Debug.Log("Hello");
}

(注意:为了良好的编程习惯,尽管我建议将其命名为 "Teleport" 以外的名称 - 将其命名为 "HandleMenuButton" 或 "MenuButtonPressed" 以保持其意图清晰;然后在其中方法,你可以调用一个单独的 "Teleport" 函数。将来如果你需要更改交互,如果保持这种分离级别,更新代码会更容易。)