NGUI下给Spriteimage添加collider后能自适应大小,但是在UGUI下Collider是默认在(0,0)位置,size为0因此写了个简单的脚本,效果如下(最后附代码 NGUI下给Sprite/image添加collider后能自适应大小
NGUI下给Spriteimage添加collider后能自适应大小,但是在UGUI下Collider是默认在(0,0)位置,size为0因此写了个简单的脚本,效果如下(最后附代码
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 initialization11 void Start () {12 gameObject = this.GetComponent();13 boxCollider2D = this.GetComponent();14 }15 16 // Update is called once per frame17 void Update () {18 if (boxCollider2D == null)19 {20 Debug.Log("can‘t find collider");21 return;22 }23 else24 {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
Unity3d — — UGUI之Box Collider自适应大小