1. 程式人生 > >獲取場景中的所有按鈕,並新增點選事件

獲取場景中的所有按鈕,並新增點選事件

void Start()
    {//初始化時 獲取 所有按鈕新增監聽
        Addlisteningevent();
    }

      public void Addlisteningevent()
    {//查詢所有按鈕
        Button[] allObj = Resources.FindObjectsOfTypeAll(typeof(Button)) as Button[];

        for (int i = 0; i < allObj.Length; i++)
        {
                switch (allObj[i].name)
                {
                    case "Button1":
                        allObj[i].onClick.AddListener(OnClick1);
                        break;
                    case "Button2":
                        allObj[i].onClick.AddListener(OnClick2);
                        break;
                    case "Button3":
                        allObj[i].onClick.AddListener(OnClick3);
                        break;
                    default:
                        break;

                }
        }

    }

    private void OnClick1()
    {
        Debug.Log("按鈕1");
    }
    private void OnClick2()
    {
        Debug.Log("按鈕2");
    }
    private void OnClick3()
    {
        Debug.Log("按鈕3");
    }