首页 > 编程语言 > 详细

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

时间:2018-09-16 20:24:52      阅读:468      评论:0      收藏: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 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

 

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

原文:https://www.cnblogs.com/QQW123/p/9657154.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!