【问题标题】:Unity, C#, 2D : how to set a UI canvas item(button) position to the same position as another gameobject?Unity、C#、2D:如何将 UI 画布项(按钮)位置设置为与另一个游戏对象相同的位置?
【发布时间】:2021-10-17 05:01:26
【问题描述】:

我试图通过代码让按钮出现在与框相同的位置,以便在调用此函数时将按钮游戏对象移动到菜单框游戏对象所在的位置

private RectTransform Bpos; 

// this var holds the box sprite
    public GameObject menu;

// this var hold the button game object
    public GameObject button;

// vector to hold position
    Vector3 pos;

void Start(){
// sets vector to box position
       pos = menu.transform.position;

       //declairs button recttransform
            Bpos = button.GetComponent<RectTransform>();

       // sets button recttransformto pos vector
       button.Bpos = pos;

}```
i am currently getting the error at line (button,Bpos = pos;)

 error CS1061: 'GameObject' does not contain a definition for 'Bpos' and no accessible extension method 'Bpos' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?)
for the life of me i cant get this to work 

【问题讨论】:

标签: c# unity3d 2d


【解决方案1】:

UI 使用 anchoredPosition 而不是 transform.position。您需要将按钮的anchoredPosition 设置为菜单的anchoredPosition。您可以通过访问 RectTransform 来获取 anchoredPosition。我会这样写:

void Start(){
   // get anchoredPosition of menu and save it in pos
   pos = menu.GetComponent<RectTransform>().anchoredPosition;

   // set anchoredPosition of the button to pos (anchoredPosition of menu)
   button.GetComponent<RectTransform>().anchoredPosition = pos

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-14
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    相关资源
    最近更新 更多