在ui上使用boxcollider的问题

  • 问题就是boxCollider不会随着UI缩放而缩放
  • 这个问题也很简单
  • 下面脚本可以实现随着recttransform来同步设置boxcollider
csharp 复制代码
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大小
            }
        }
    }
}
相关推荐
ZC跨境爬虫6 小时前
跟着 MDN 学CSS day_44:响应式设计——让网页适配所有屏幕的完整指南
前端·css·ui·html·tensorflow
ZC跨境爬虫9 小时前
跟着 MDN 学CSS day_43:CSS布局挑战——从浮动到弹性盒与栅格的综合实践
前端·css·ui·html·tensorflow
夜空孤狼啸9 小时前
Vue Data UI:这不是图表库,是数据可视化 UI 平台
vue.js·ui·信息可视化
ZC跨境爬虫1 天前
跟着 MDN 学CSS day_37:(从文档流到粘性定位的底层原理)
前端·javascript·css·ui·html
G_dou_1 天前
Flutter三方库适配OpenHarmony【compass】罗盘 UI 项目完整实战
flutter·ui
ZC跨境爬虫1 天前
跟着 MDN 学CSS day_40:(Flexbox实战技能测试)
前端·css·ui·html·tensorflow
ZC跨境爬虫1 天前
跟着 MDN 学CSS day_36:(float、clear与BFC深度解析)
前端·javascript·css·ui·交互
豆豆1 天前
2026实测:AI生成UI设计稿后,如何优雅集成到PageAdmin CMS?(附标签替换代码)
人工智能·ui·cms·建站系统·ai工具·ai建站
爱吃大芒果1 天前
鸿蒙 ArkUI 架构蓝图:MoodLite 的 UI 渲染与数据逻辑解耦实践
ui·架构·harmonyos