Unity, c#, 2D:如何将UI画布项目(按钮)的位置设置为与另一个游戏对象相同的位置?



我试图有一个按钮出现在相同的位置,通过代码框,这样当调用这个函数移动按钮的游戏对象,无论在哪里菜单框的游戏对象

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 

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
}

最新更新