前言
在使用Unity进行2D开发的时候,经常会出现屏幕适配的问题,UI因自适应而改变了自身的大小之后,与之相关的BoxCollider2D组件的大小却依然还是原本的大小,故做此记录。
正文
废话不多说,直接上代码~
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class BoxColliderAdjust : MonoBehaviour { public bool isAutoAdjust = false; private BoxCollider2D boxCollider2D; private RectTransform gameObjectRect;
void Start() { gameObjectRect = GetComponent<RectTransform>(); boxCollider2D = GetComponent<BoxCollider2D>(); }
void Update() { if (boxCollider2D != null) { if (isAutoAdjust == true) { boxCollider2D.offset = gameObjectRect.rect.center; boxCollider2D.size = new Vector2(gameObjectRect.rect.width, gameObjectRect.rect.height); } } else { Debug.LogError("Can't find any BoxCollider2D"); } } }
|
to be continued…