有过一个需求需要一个item,两个item,三个item(不一定有多少个子节点)不同情况都要居中
有两个方法解决:
1.只需要在uiscrollview上的resetPosition 设为0.5,调一下resetPosition自动居中
2.如果本身在uiScrollview上就不能这么用了,两个uiscrollview不能重叠嘛。
所以写了个脚本负责计算每个子节点的localposition。
using UnityEngine; using System.Collections; using System.Collections.Generic; public class CenterChildTransfroms { UIAnchor m_anchor; private Transform m_transform; private GameObject m_containerGameObject; private float m_spacing; public CenterChildTransfroms(Transform transform, GameObject containerGameObject,Camera camera, float spacing =0) { m_transform = transform; m_containerGameObject = containerGameObject; m_spacing = spacing; m_anchor = m_transform.GetComponent<UIAnchor>(); if (m_anchor == null) m_anchor = m_transform.gameObject.AddComponent<UIAnchor>(); m_anchor.uiCamera = camera; m_anchor.container = containerGameObject; m_anchor.side = UIAnchor.Side.Center; m_anchor.enabled = false; } public void RepositionChildTransfroms() { float totalWidth = 0; List<Transform> childTrans = new List<Transform>(); List<float> childTransBoundSizeX = new List<float>(); foreach (Transform t in m_transform) { if(t.gameObject.activeSelf) { childTrans.Add(t); float width = (NGUIMath.CalculateRelativeWidgetBounds(t).size.x * t.localScale.x) + m_spacing; totalWidth += width; childTransBoundSizeX.Add(width); } } if(childTrans.Count > 0) { //先计算好第一个transform坐标 childTrans[0].localPosition = new Vector3((-totalWidth / 2 + childTransBoundSizeX[0] / 2), childTrans[0].localPosition.y, childTrans[0].localPosition.z); for(int i =1;i<childTrans.Count;i++) { float lastTransBoundX = childTransBoundSizeX[i - 1] / 2; float transBoundX = childTransBoundSizeX[i] / 2; childTrans[i].localPosition = new Vector3(childTrans[i - 1].localPosition.x + lastTransBoundX + transBoundX , childTrans[i].localPosition.y,childTrans[i].localPosition.z); } } CenterTransform(); } public void CenterTransform() { m_anchor.enabled = true; } }
这里可以看到使用前是需要传递父节点transform,居中在哪个GameObject的那个gameObject,传入所属UIcamera,和每个子节点之间间隙。
其实也就是在父节点上添加一个锚点UIAnchor,把需要的参数(cotainerGameObject,Camera)塞进去.
计算时先计算总宽,算出并摆放第一个transform的localPosition,之后根据这个坐标进行一个个计算
时间: 2024-11-12 09:17:58