程序员必知:UnityUGUI锚点快速定位(自适应)

简介: 程序员必知:UnityUGUI锚点快速定位(自适应)

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() == null)

continue;

AnchorCon(objs【i】);

}//代码效果参考:http://www.ezhiqi.com/zx/art_22.html

}//代码效果参考:http://www.ezhiqi.com/bx/art_1905.html

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 localRect = obj.GetComponent();

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;

}//代码效果参考:http://www.ezhiqi.com/bx/art_3895.html

}

踩的坑:(纳闷的一笔)

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

最后解决办法

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

比手动拖要快多了

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

相关文章
|
3月前
|
前端开发 JavaScript
网页简单布局之结构与表现原则分享
网页简单布局之结构与表现原则分享
94 9
|
4月前
|
计算机视觉 Python
目标检测笔记(四):自适应缩放技术Letterbox完整代码和结果展示
自适应缩放技术Letterbox通过计算缩放比例并填充灰边像素,将图片调整为所需尺寸,保持原始比例不变,广泛应用于目标检测领域。
152 1
目标检测笔记(四):自适应缩放技术Letterbox完整代码和结果展示
|
8月前
|
程序员
程序员必知:UnityUGUI锚点快速定位(自适应)
程序员必知:UnityUGUI锚点快速定位(自适应)
72 1
|
6月前
|
图形学
小功能⭐️Unity 如何判断物体是否在摄像机视野内或外
小功能⭐️Unity 如何判断物体是否在摄像机视野内或外
|
9月前
|
移动开发 前端开发 iOS开发
H5页面布局之图片液态化(自适应)处理简述
H5页面布局之图片液态化(自适应)处理简述
76 0
H5页面布局之图片液态化(自适应)处理简述
|
9月前
|
前端开发 容器
如何实现一个两栏布局,右侧自适应?三栏布局中间自适应?
要实现一个两栏布局,右侧自适应的效果,可以使用 CSS 的 Flexbox 或 Grid 布局来实现。以下是使用 Flexbox 实现的示例:
94 1
|
9月前
|
索引
消除游戏中图标下落的原理和实现
消除游戏中图标下落的原理和实现
65 1
|
前端开发 开发者 容器
分类页-两栏自适应 |学习笔记
快速学习 分类页-两栏自适应
108 0
分类页-两栏自适应 |学习笔记
|
开发者
HTML标签- 锚点定位|学习笔记
HTML标签- 锚点定位|学习笔记
165 0
HTML标签- 锚点定位|学习笔记
|
前端开发
CSS样式更改——框模型、定位、浮动、溢出
CSS样式更改——框模型、定位、浮动、溢出
137 0
CSS样式更改——框模型、定位、浮动、溢出