在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跨境爬虫13 小时前
UI前端美化技能提升日志day8:(Watch专区字体优化+尺寸校准+视觉重构+结构分层)
前端·ui·重构·html
早起傻一天~G15 小时前
vue2+element-UI表单封装
前端·vue.js·ui
报错小能手16 小时前
Swift UI 用 MVVM 架构 Combine EventBus 实现待办清单
开发语言·ui·swift
EaseUI1 天前
【Ease UI】2026-04-24 项目更新:增加多种风格登录页,增加菜单风格切换
ui
ZC跨境爬虫1 天前
UI前端美化技能提升日志day7:(原生苹方字体全局适配+合规页脚完整像素级落地)
前端·javascript·ui·html·交互
Ulyanov1 天前
《PySide6 GUI开发指南:QML核心与实践》 第十篇:综合实战——构建完整的跨平台个人管理应用
开发语言·python·qt·ui·交互·qml·雷达电子战系统仿真
Aotman_1 天前
Element UI 表格搜索高亮
前端·javascript·vue.js·ui·elementui
久爱物联网2 天前
【WinForm UI控件系列】散点图/折线图控件 (支持数值型、时间型、字符串型)
ui·winformui控件·c#控件ui·桌面应用ui控件·gdi绘制控件·散点图曲线图控件·时间型曲线图
RReality2 天前
【Unity Shader URP】屏幕空间扭曲后处理(Screen Space Distortion)实战教程
ui·unity·游戏引擎·图形渲染·材质
Ulyanov2 天前
《PySide6 GUI开发指南:QML核心与实践》 第八篇:性能优化大师——QML应用性能调优实战
python·qt·ui·性能优化·qml·系统仿真