NGUI下給Sprite/image添加collider后能自適應大小,但是在UGUI下Collider是默認在(0,0)位置,size為0
因此寫了個簡單的腳本,效果如下(最后附代碼)
1.如下圖添加Box Collider 2D后的默認位置與大小
2.給需要的物體添加Script並運行后的效果:
代碼:

1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class BoxColliderAdjust : MonoBehaviour { 6 7 public bool AdjustBoxCollider = false; 8 private BoxCollider2D boxCollider2D; 9 private RectTransform gameObject; 10 // Use this for initialization 11 void Start () { 12 gameObject = this.GetComponent<RectTransform>(); 13 boxCollider2D = this.GetComponent<BoxCollider2D>(); 14 } 15 16 // Update is called once per frame 17 void Update () { 18 if (boxCollider2D == null) 19 { 20 Debug.Log("can't find collider"); 21 return; 22 } 23 else 24 { 25 26 if (AdjustBoxCollider == true) 27 { 28 boxCollider2D.offset = gameObject.rect.center; //把box collider設置到物體的中心 29 boxCollider2D.size = new Vector2(gameObject.rect.width, gameObject.rect.height); //改變collider大小 30 } 31 } 32 } 33 }