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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM