Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    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:
    233
    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:
    233
    The solution is that UI elements should be moved by buttonsRT.anchoredPosition and target.anchoredPosition.