UI自动绑定锚点


//Criado por Rodrigo de Toni

using UnityEngine;
using UnityEditor;
using System.Collections;


public class SnapAnchorsEditor : Editor
{
    

	[MenuItem("GameObject/Snap Anchors/in this and it's children", false, 0)]
    static void SweepingSnapAnchorsStatic()
    {
        Debug.Log("Snaping anchors of ''" + Selection.activeTransform.gameObject.name + "'' and its children.");

		StaticSweepingSnapAnchors(Selection.activeGameObject);
    }

	[MenuItem("GameObject/Snap Anchors/in this", false, 0)]
	static void SnapAnchorsStatic()
	{
		Debug.Log("Snaping anchors of ''" + Selection.activeTransform.gameObject.name + ".");
		StaticSnapAnchors(Selection.activeGameObject);
	}
		

	public static void StaticSnapAnchors(GameObject o){

		RectTransform recTransform = null;
		RectTransform parentTransform = null;
	
		if (o.transform.parent != null) {
			if (o.gameObject.tag != "IgnoreSnapAnchors") {
				if (o.GetComponent<RectTransform> () != null)
					recTransform = o.GetComponent<RectTransform> ();
				else {
					Debug.LogError (o.name + " Doesn't have RectTransform. SnapAnchors must be used only with UI objects. Please select a objet with RectTransform. Returning function.");
					return;
				}

				if (parentTransform == null) {
					parentTransform = o.transform.parent.GetComponent<RectTransform> ();
				}
				Undo.RecordObject (recTransform,"Snap Anchors");

				Vector2 offsetMin = recTransform.offsetMin;
				Vector2 offsetMax = recTransform.offsetMax;

				Vector2 anchorMin = recTransform.anchorMin;
				Vector2 anchorMax = recTransform.anchorMax;

				Vector2 parent_scale = new Vector2 (parentTransform.rect.width, parentTransform.rect.height);


				recTransform.anchorMin = new Vector2 (
					anchorMin.x + (offsetMin.x / parent_scale.x),
					anchorMin.y + (offsetMin.y / parent_scale.y));

				recTransform.anchorMax = new Vector2 (
					anchorMax.x + (offsetMax.x / parent_scale.x),
					anchorMax.y + (offsetMax.y / parent_scale.y));

				recTransform.offsetMin = Vector2.zero;
				recTransform.offsetMax = Vector2.zero;
			}
		}

	}
    public static void StaticSweepingSnapAnchors(GameObject o)
    {
		StaticSnapAnchors (o);
        for (int i = 0; i < o.transform.childCount; i++)
        {
			StaticSweepingSnapAnchors(o.transform.GetChild(i).gameObject);
        }   
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值