UGUI优化技巧之Box Collider自适应大小

发表于2018-10-25
评论0 5.8k浏览
NGUI下给Sprite/image添加collider后能自适应大小,但是在UGUI下Collider是默认在(0,0)位置,size为0,如何实现Collider自适应大小呢,下面就给大家分享一个简单的脚本,效果如下(最后附代码)

1.如下图添加Box Collider 2D后的默认位置与大小

2.给需要的物体添加Script并运行后的效果:




代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoxColliderAdjust : MonoBehaviour {
    public bool AdjustBoxCollider = false;
    private BoxCollider2D boxCollider2D;
    private RectTransform gameObject;
    // Use this for initialization
     void Start () {
        gameObject = this.GetComponent<RectTransform>();
        boxCollider2D = this.GetComponent<BoxCollider2D>();
    }
    // Update is called once per frame
    void Update () {
        if (boxCollider2D == null)
        {
            Debug.Log("can't find collider");
            return;
        }
        else
        {
            if (AdjustBoxCollider == true)
            {
                boxCollider2D.offset = gameObject.rect.center;      //把box collider设置到物体的中心
                boxCollider2D.size = new Vector2(gameObject.rect.width, gameObject.rect.height);    //改变collider大小
            }
        }
    }
}
BoxColliderAdjust

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引