给Unity中的UI的《button》和《Slider》用脚本添加碰撞体

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/// <summary>
/// 给所有的按钮创建碰撞体
/// </summary>
public class CreateColliderForButton : MonoBehaviour {

    //public GameObject canvas;
    private Button[] _buttonArray;          //按钮
    private Slider[] _sliderArray;          //滑动条

// Use this for initialization
void Start () {
            _buttonArray = this.GetComponentsInChildren<Button>(true);            //获取所有的Button按钮
            _sliderArray = this.GetComponentsInChildren<Slider>(true);              //获取所有的slider
        //给每一个按钮创建一个碰撞体
        for(int i = 0; i < _buttonArray.Length; i++)
        {
            //判断按钮是否有碰撞器
            if (_buttonArray[i].gameObject.GetComponent<Collider>() == null)
            {
                //创建碰撞器
                var buttonSize = _buttonArray[i].gameObject.GetComponent<RectTransform>().sizeDelta;
                BoxCollider button_BoxCollider = _buttonArray[i].gameObject.AddComponent<BoxCollider>();
                button_BoxCollider.size = new Vector3(buttonSize.x,buttonSize.y,2);
                button_BoxCollider.center =new Vector3(0, 0, 1);
            }
        }


        //判断滑动条是否有碰撞体
        for(int j = 0; j < _sliderArray.Length; j++)
        {
            //Debug.Log("=============================");
            //Debug.Log(_sliderArray[j].name);
            if (_sliderArray[j].gameObject.GetComponent<Collider>() == null)
            {
                //创建碰撞器
                var sliderSize = _sliderArray[j].gameObject.GetComponent<RectTransform>().sizeDelta;
                BoxCollider slider_BoxCollider = _sliderArray[j].gameObject.AddComponent<BoxCollider>();
                slider_BoxCollider.size = new Vector3(sliderSize.x, sliderSize.y, 2);
                slider_BoxCollider.center = new Vector3(0, 0, 1);
            }
        }
}

}


//脚本需要添加在Canvas上,确保对所有的按钮和滑动条都能添加上。

猜你喜欢

转载自blog.csdn.net/qq_34444468/article/details/79635707
今日推荐