我正在使用 Unity 中的按鈕進行練習,我試圖弄清楚如何在不使用檢查器中的 OnClick 的情況下為按鈕分配不同的方法,所以我想出了這個。
public class UIButtons : MonoBehaviour
{
void Start()
{
var buttons = FindObjectsOfType<Button>(); //I should probably have this outside of this method
foreach (Button button in buttons)
{
button.onClick.AddListener(() => ButtonPressed(button));
}
}
void ButtonPressed(Button button)
{
switch (button.name)
{
case "MMPlayButton": //The main menu play button
Debug.Log("Play button pressed");
break;
case "PlayButton":
Debug.Log("Play button pressed");
break;
case "SettingsButton":
Debug.Log("Settings button pressed");
break;
case "QuitButton":
Debug.Log("Quit button pressed");
break;
default:
Debug.LogWarning("Button doesn't have a case: " button.name);
//could do some kind of pop up message saying the button pressed isn't available or something
break;
}
}
}
我知道這可以作業,但是,我想這是一種可怕的做事方式,因為它使用名稱,所以如果我要更改名稱或打錯字,它會中斷,或者我遇到的問題是按鈕是否有同名,如果我添加更多按鈕,我將不得不添加更多案例,然后它可能會變成一團糟。
不過我可能是錯的,也許這是一個不錯的主意,但我對此表示懷疑,因此尋求一些幫助。
uj5u.com熱心網友回復:
您可以通過使用繼承來簡化這一點。為所有要使用的按鈕創建一個基類,即。UIButtonBase
具有OnButtonPressed
虛方法。然后創建繼承此基類并覆寫該OnButtonPressed
方法的特定按鈕。
基類
public class UIButtonBase: MonoBehaviour
{
protected virtual void Awake()
{
var button = GetComponent<Button>();
if (button)
{
button.onClick.AddListener(() => OnButtonPressed());
}
else
{
Debug.Log(name " does not have a Button component!");
}
}
protected virtual void OnButtonPressed()
{
Debug.Log("UIButtonBase::OnButtonPressed()");
}
}
一個按鈕的具體實作
public class SettingsButton : UIButtonBase
{
protected override void OnButtonPressed()
{
Debug.Log("SettingsButton::OnButtonPressed()");
// If you want the base functionality as well, add..
//
base.OnButtonPressed();
}
}
對于設定,創建一個按鈕并將此腳本添加到其中。您可能需要將GetComponent
in Awake
(UIButtonBase) 更改為GetComponentInParent
或GetComponentInChildren
,具體取決于您的游戲物件層次結構。您還可以在 UIButtonBase 腳本中公開 Button 組件并使用該參考。
uj5u.com熱心網友回復:
我知道這不是一個好的答案,但如果我是你,我會為不同的按鈕制作不同的檔案。像 SettingButton.cs、PlayButton.cs 等。
這種方法不會給您的代碼增加大量負擔,但隨著按鈕功能的增加,這種方法將極大地幫助您保持代碼的組織性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/467343.html