Unity3d — — UGUI之Box Collider自适应大小

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 }
BoxColliderAdjust

 

posted @ 2018-09-16 20:00  QQW的进化之旅  阅读(2829)  评论(0编辑  收藏  举报