Unity UGUI锚点快速定位(自适应)

1.编辑器脚本需要放到Editor文件夹下面

简单操作,快速让锚点分布在组件四个顶点

选中组件(可以单选,可以多选)   点击Tools/自适应锚点

 

 

 代码如下:

复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class AnchorController 
{
    [MenuItem("Tools/自适应锚点")]
    private static void SelectionAnchor()
    {
        GameObject[] objs = Selection.gameObjects;
        for (int i = 0; i < objs.Length; i++)
        {
            if (objs[i].GetComponent<RectTransform>() == null)
                continue;
            AnchorCon(objs[i]);
        }
    }

    private static void AnchorCon(GameObject obj)
    {
        //位置信息
        Vector3 partentPos = obj.transform.parent.position;
        Vector3 localPos = obj.transform.position;
        //------获取rectTransform----
        RectTransform partentRect = obj.transform.parent.GetComponent<RectTransform>();
        RectTransform localRect = obj.GetComponent<RectTransform>();
        float partentWidth = partentRect.rect.width;
        float partentHeight = partentRect.rect.height;
        float localWidth = localRect.rect.width * 0.5f;
        float localHeight = localRect.rect.height * 0.5f;
        //---------位移差------
        float offX = localPos.x - partentPos.x;
        float offY = localPos.y - partentPos.y;

        float rateW = offX / partentWidth;
        float rateH = offY / partentHeight;
        localRect.anchorMax = localRect.anchorMin = new Vector2(0.5f + rateW, 0.5f + rateH);
        localRect.anchoredPosition = Vector2.zero;

        partentHeight = partentHeight * 0.5f;
        partentWidth = partentWidth * 0.5f;
        float rateX = (localWidth / partentWidth) * 0.5f;
        float rateY = (localHeight / partentHeight) * 0.5f;
        localRect.anchorMax = new Vector2(localRect.anchorMax.x + rateX, localRect.anchorMax.y + rateY);
        localRect.anchorMin = new Vector2(localRect.anchorMin.x - rateX, localRect.anchorMin.y - rateY);
        localRect.offsetMax = localRect.offsetMin = Vector2.zero;
    }

}
复制代码

 

踩的坑:(纳闷的一笔)

在预设物里面,用上面工具自适应之后保存,换一个预设物,在重新进刚刚的预设物里面,发现刚刚预设物的锚点跟没应用之前是一样的

最后解决办法

先取消自动保存(AutoSave),然后随便点击一个组件的锚点,用鼠标拖动一下,再用上面的锚点工具应用锚点,最后勾上自动保存,在切换一下预设物回来,发现锚点应用成功

比手动拖要快多了

 

如果喜欢,请点个赞吧,感谢

 

posted @   剑起苍穹  阅读(868)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
历史上的今天:
2019-12-03 unity噪声消融效果Shader实现
/*鼠标点击特效*/
点击右上角即可分享
微信分享提示