Odd*_*una 4 c# unity-game-engine
我是 unity3d 的初学者,我正在努力使 Ui 锚点最小最大位置与移动时按钮位置相同,我的目标是尝试实现如下图所示。
正如您所看到的,当按钮移动锚点时,最小最大不跟随它,我应该以什么方式使用 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);
}
Run Code Online (Sandbox Code Playgroud)
提前致谢!
我已经弄清楚了,为了实现我的目标,我修改了一些我在互联网上发现有用的脚本。这是代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
为了完成这项工作,我将此脚本保存为 C#,之后我将其附加到任何 UI 对象,当您运行 Unity 游戏时,UI 锚点将自动围绕 UI 对象调整自身大小。我发现这在实例化预制件并循环它时很有用,因为你无法真正更改锚点。
来源:http ://answers.unity3d.com/questions/782478/unity-46-beta-anchor-snap-to-button-new-ui-system.html