給Unity中的UI的《button》和《Slider》用指令碼新增碰撞體
阿新 • • 發佈:2019-01-26
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);
}
}
}
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);
}
}
}
}