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);
}
}
}
}




