【问题标题】:A script that makes anchor min max positioned at Gameobject ui corners?一个使锚定最小值最大值定位在 Gameobject ui 角落的脚本?
【发布时间】:2016-09-04 13:37:08
【问题描述】:

我是 unity3d 的初学者,我正在努力使 Ui 锚最小最大位置与移动时的按钮位置相同,我的目标是尝试实现如下图所示。

正如您所看到的,当按钮移动锚时 min max 没有跟随它,我应该以什么方式使用 C# 解决这个问题?目前我使用以下脚本移动按钮:

    public GameObject SaleButtonPrefab;

    //To loop all the list
    for(int i = 0; i < playerList.Count; i++)
    {

        //Instantiate the button prefab and make a parent
        GameObject nu = Instantiate(SaleButtonPrefab) as GameObject;
        nu.transform.SetParent(ParentButton.transform, false);

        //To set the position
        nu.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, (i*-301) - 0);

    }

提前致谢!

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    我已经想通了,为了实现我的目标,我修改了一些我在互联网上发现有用的脚本。这是代码:

    using UnityEngine;
    using System.Collections;
    using UnityEngine.UI;
    
    public class GUITest : MonoBehaviour 
    {
    
        private RectTransform t;
        private RectTransform pt;
    
        void Start()
        {
            t = gameObject.GetComponent<RectTransform>();
            pt = gameObject.GetComponent<RectTransform>().parent as RectTransform;
    
            if(t == null || pt == null) return;
    
            Vector2 newAnchorsMin = new Vector2(t.anchorMin.x + t.offsetMin.x / pt.rect.width,
                                             t.anchorMin.y + t.offsetMin.y / pt.rect.height);
            Vector2 newAnchorsMax = new Vector2(t.anchorMax.x + t.offsetMax.x / pt.rect.width,
                                             t.anchorMax.y + t.offsetMax.y / pt.rect.height);
    
            t.anchorMin = newAnchorsMin;
            t.anchorMax = newAnchorsMax;
            t.offsetMin = t.offsetMax = new Vector2(0, 0);
        }
    }
    

    为了完成这项工作,我将此脚本保存为 C#,然后将其附加到任何 UI 对象,当您运行统一游戏时,UI 锚将自动围绕 UI 对象调整大小。我发现这在实例化预制件并循环它时很有用,因为你不能真正改变锚点。

    来源:http://answers.unity3d.com/questions/782478/unity-46-beta-anchor-snap-to-button-new-ui-system.html

    【讨论】:

      猜你喜欢
      • 2012-03-20
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      相关资源
      最近更新 更多