Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Bug Moving UI elements over time produces bug.

Discussion in 'UGUI & TextMesh Pro' started by Brother_77, Oct 21, 2021.

  1. Brother_77

    Brother_77

    Joined:
    Feb 8, 2019
    Posts:
    205
    Hi, I have a button that is moved with the code below, but it randomly sometimes gets stuck without reaching the target, any ideas would be much appreciated.

    Code (CSharp):
    1.     public RectTransform buttonsRT; // button RT used to move it.
    2.     public RectTransform targetPosOneRect; // empty gameobject on the canvas that is used as a target.
    3.     public RectTransform targetPosTwoRect;
    4.  
    5.     public void Execute()
    6.     {
    7.         StartCoroutine(PlayButtonCoroutine(targetPosOneRect.position, targetPosTwoRect.position, 750.0f, 1000.0f)); // Button pressed
    8.     }
    9.  
    10.     private IEnumerator PlayButtonCoroutine(Vector3 posOne, Vector3 posTwo, float speedOne, float speedTwo)
    11.     {
    12.         yield return MoveRectTransformToTarget(buttonsRT, posOne, speedTwo);
    13.         yield return MoveRectTransformToTarget(buttonsRT, posTwo, speedTwo);
    14.     }
    15.  
    16.     private IEnumerator MoveRectTransformToTarget(RectTransform objectToMove, Vector3 posTarget, float speed)
    17.     {
    18.         while (objectToMove.transform.position != posTarget)
    19.         {
    20.             objectToMove.transform.position = Vector3.MoveTowards(objectToMove.transform.position, posTarget, speed * Time.deltaTime);
    21.             yield return null;
    22.         }
    23.     }
     
  2. Brother_77

    Brother_77

    Joined:
    Feb 8, 2019
    Posts:
    205
    The solution is that UI elements should be moved by buttonsRT.anchoredPosition and target.anchoredPosition.