Button Problem

So I’m trying to get a button to move with a panel. The button opens the panel, but then moves very far to the right of the Canvas page.


After click the button the panel opens but the button teleports to the right.

Here’s my script for the Panel Opener.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PanelOpener : MonoBehaviour
{
    public GameObject Panel;
    public Camera cam;
    private RectTransform rectTransform;
    float startX;

    void Start(){
        rectTransform = Panel.GetComponent<RectTransform>();
        startX = GetComponent<RectTransform>().anchoredPosition.x;

    }

    public void OpenPanel() {
        if(Panel != null) {
           
            Vector3 screenPos = cam.WorldToScreenPoint(rectTransform.sizeDelta);
            float offset = (screenPos.x) * rectTransform.localScale.x;
            bool newState = !Panel.activeSelf;
            Panel.SetActive(newState);
            Vector2 anchoredPosition = GetComponent<RectTransform>().anchoredPosition;
            if(newState){
                // move button to left
                GetComponent<RectTransform>().anchoredPosition = new Vector2(offset, anchoredPosition.y);//+= new Vector2(-offset, 0);
            }else{
                GetComponent<RectTransform>().anchoredPosition = new Vector2(startX, anchoredPosition.y);
            }
        }
    }
}


If I understand correctly what you want to do, you don’t need any code for that. Just put the button inside the panel in the scene hierarchy, and anchor its position to the bottom-right corner of its parent.

There is a Canvas object, in side the Canvas object there is a button and a panel. I don’t want the button that closes and open the panel to be inside the panel.

You’ve said what happens, and what you don’t want it to do, but you haven’t told us what you do want. You want the button to move, but how? I’m guessing you want the button to shift along with the panel as it pulls out from the side, like so:


If that’s the case, what @JoeStrout said was right… You can still make the button a child of the panel, and anchored to the lower left corner, but just move its x position enough into the negatives to have it sit outside the area of the panel itself.

I use Unity UI every day for my job and am extremely competent with it, so if you give me more information to go on, I can tell you how to do it. But you’ve gotta give us more to work with first.

2 Likes