Search Unity

Question How to get and set position of a UI element

Discussion in 'UGUI & TextMesh Pro' started by kader1081, Mar 8, 2023.

  1. kader1081

    kader1081

    Joined:
    Oct 16, 2021
    Posts:
    379
    Hi I am trying to get position of a button then I want to move an Image to button location but it doesn't work.
    Code (CSharp):
    1. public GameObject Cursor;
    2.     void Start()
    3.     {
    4.        
    5.     }
    6.  
    7.     // Update is called once per frame
    8.     void Update()
    9.     {
    10.        
    11.     }
    12.  
    13.     public void OnPointerEnter(PointerEventData pointerEventData)
    14.     {
    15.         Cursor.SetActive(true);
    16.          Cursor.GetComponent<RectTransform>().position =
    17. gameObject.GetComponent<RectTransform>().position;
    18.     }
    19.  
    20.     public void OnPointerExit(PointerEventData pointerEventData)
    21.     {
    22.         Cursor.SetActive(false);
    23.     }
     
  2. kader1081

    kader1081

    Joined:
    Oct 16, 2021
    Posts:
    379
    I solved the problem first you have to be sure that two objects have to be same parents child and anchors have to be same align for example center after that you use rectransform.anchorposition