这样做的正确方法是什么?
这是我的代码,但我不认为这是正确的方法
public class buttons : MonoBehaviour {
public Button play;
public Button shop;
public Button exit;
// Use this for initialization
void Start () {
Button bplay=play.GetComponent<Button>();
Button bshop=shop.GetComponent<Button>();
Button bexit=exit.GetComponent<Button>();
bplay.onClick.AddListener(()=>loads("level"));
bshop.onClick.AddListener(()=>loads("shop"));
bexit.onClick.AddListener(()=>loads("exit"));
}
void loads(System.String scenename)
{
if(scenename=="level")
Application.LoadLevel("level_1");
else if(scenename=="shop")
Application.LoadLevel("Shop_menu");
else if(scenename=="exit")
Application.Quit();
}
}
答案 0 :(得分:1)
第一个问题是你在Start()
函数中所做的一切。 play
,shop
和exit
变量已经是Button
类型。无需执行您在GetComponent
函数中执行的所有Start()
操作。这些是冗余。您可以直接使用该公共变量:play.onClick.AddListener
。
其次,最好比较Button
而不是string
的实例,因为它更快。要做到这一点,您应该使加载函数以Button
为参数而不是string
。
此外,Application.LoadLevel
函数现已弃用。现在应该使用SceneManager.LoadScene
来加载新场景。请务必在顶部添加using UnityEngine.SceneManagement;
,以便您可以使用SceneManager.LoadScene
。
最后,应在OnEnable
函数中注册事件。您还应该使用OnDisable
函数在Button.onClick.RemoveListener
函数中取消注册它。
public class buttons : MonoBehaviour
{
public Button play;
public Button shop;
public Button exit;
void OnEnable()
{
play.onClick.AddListener(() => loads(play));
shop.onClick.AddListener(() => loads(shop));
exit.onClick.AddListener(() => loads(exit));
}
void OnDisable()
{
play.onClick.RemoveListener(() => loads(play));
shop.onClick.RemoveListener(() => loads(shop));
exit.onClick.RemoveListener(() => loads(exit));
}
void loads(Button buttonPressed)
{
if (buttonPressed == play)
SceneManager.LoadScene("level_1");
else if (buttonPressed == shop)
SceneManager.LoadScene("Shop_menu");
else if (buttonPressed == exit)
Application.Quit();
}
}