[英]Subscribe event Unity VR
Unity共享不同的資產/腳本以使用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");
}
}
}
但是我有一個錯誤:“錯誤CS0123:方法或委托VRStandardAssets.Menu.GetDiscover.Teleport()' parameters do not match delegate
System.Action(VRStandardAssets.Menu.MenuButton)的參數VRStandardAssets.Menu.GetDiscover.Teleport()' parameters do not match delegate
”。
這意味着什么 ? 我只是在尋找調用事件的最簡單方法...
我也嘗試使用了委托方法,但是它也行不通...也許我不太了解事件系統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”功能。將來,如果您需要更改交互,那么如果您保持這種分離水平,將更容易更新代碼。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.