38

场景所有Button添加点击事件_005.1-腾讯游戏学院

 5 years ago
source link: http://gad.qq.com/article/detail/286247
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
算是一个扩展,游戏中很多按键都会有点击音效,因为按键太多,如果每个按键都手动绑定或者代码绑定监听事件,都比较繁琐,而且容易遗漏。
我的做法是获取场景中所有的Button,统一添加监听事件不需要单独添加音效事件。
待实现功能:
1. 如果不同的按键有不同的点击音效,可以在命名上做一下区分,添加一个后缀,在统一添加监听事件时,根据不同的后缀名,来绑定不同事件。
2. 如果场景中按键较多,可以利用协程,分批次进行处理,将运算量分散。
3. 如果有动态加载的按键Object,现有2个方案可供参考(未实际测试,只是一个设想),一是直接获取Prefab添加监听事件,二是在动态加载的过程中,判断是否有Button组件,有则添加事件。
目前先实现基础功能,项目中可根据实际情况,继续扩展 ··· ···
        void GetAllButtonAddListener()
        {
            //获取场景所有物体
            GameObject[] allObj = Resources.FindObjectsOfTypeAll(typeof(GameObject)) as GameObject[];
            int btnCount = 0;
            Button tmpButton;
            for (int i = 0; i < allObj.Length; i++)
            {
                tmpButton = allObj[i].GetComponent<Button>();
                if (tmpButton != null)
                {
                    btnCount++;
                    tmpButton.onClick.AddListener(() => SoundManager.instance.PlaySound(Clip.button));
                }
            }
            Debug.Log("<color=green> 当前场景共有:物体 </color>" + allObj.Length + "<color=green> 个,Button组件 </color>" + btnCount + "<color=green> 个 </color>");
        }

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK