程序员必知: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),然后随便点击一个组件的锚点,用鼠标拖动一下,再用上面的锚点工具应用锚点,最后勾上自动保存,在切换一下预设物回来,发现锚点应用成功

比手动拖要快多了

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

相关文章
|
10月前
|
存储 安全 编译器
C++学习过程中的一些值得注意的小点(1)
C++学习过程中的一些值得注意的小点(1)
|
6月前
|
小程序
小程序消除图片下边距的三个方法
小程序消除图片下边距的三个方法
144 69
|
5月前
|
计算机视觉 Python
目标检测笔记(四):自适应缩放技术Letterbox完整代码和结果展示
自适应缩放技术Letterbox通过计算缩放比例并填充灰边像素,将图片调整为所需尺寸,保持原始比例不变,广泛应用于目标检测领域。
171 1
目标检测笔记(四):自适应缩放技术Letterbox完整代码和结果展示
|
9月前
|
程序员
程序员必知:UnityUGUI锚点快速定位(自适应)
程序员必知:UnityUGUI锚点快速定位(自适应)
76 1
|
7月前
|
图形学
小功能⭐️Unity 如何判断物体是否在摄像机视野内或外
小功能⭐️Unity 如何判断物体是否在摄像机视野内或外
|
10月前
|
索引
消除游戏中图标下落的原理和实现
消除游戏中图标下落的原理和实现
66 1
|
10月前
|
开发者
所有消除游戏背后都有一张看不见的网格
所有消除游戏背后都有一张看不见的网格
117 0
|
开发者
所有消除游戏背后那张看不见的网格
观察一下上方的这一系列各种各样的消除游戏的图片,它们都有着这样的一个共同点,就是都是按照行列进行布局,有 7 行 7 列,有 10 行 10 列的。这样的行列布局是不是特别的像一个“网格”?这就是我们今天要讲的,所有消除游戏背后都有的那张看不见的“网格”。
124 0
|
前端开发
有意思!不规则边框的生成方案
有意思!不规则边框的生成方案
219 0
有意思!不规则边框的生成方案
|
前端开发
css布局技巧-文字围绕浮动元素巧妙运用
解释 我们前面讲浮动的时候说道浮动的元素会“飞起来”,不占有位置,会破毁标准流,导致浮动的元素下面的标准流会跑到浮动元素的位置被浮动的元素压住,但是,我们之前在浮动那一节说过,浮动产生的目的就是让文字围绕浮动元素的,即浮动的盒子不会压住文字,利用这个特性可以很好的简化某些布局。
302 0
css布局技巧-文字围绕浮动元素巧妙运用