RectTransform and distance between two objects

Dear all,

I’ve recently applied a Canvas component to my Player component and the Transform component of the GameObject became RectTransform. So far so good. The problem is when I want to calculate the distance between another GameObject which also has Canvas and of course a RectTransform component.

The following code snippet just don’t work:

float distance = (transform.position - player.position).sqrMagnitude;

The “distance” is always very large even when the two objects are touching each other. Any help will be much appreciated.

To anyone else that is working with RectTransforms (but looking for the distance between two GUI/UI elements), I’ve spent a good chunk of the day attempting to find distance (in various ways) but the distance always returned 0f.

After some debugging, I realized that the canvas just wasn’t being updated fast enough (when using Awake or Start functions). The workaround will look something like this:

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

public class MyClassName : MonoBehaviour {

private RectTransform elementA;
private RectTransform elementB;

void Start () {
    StartCoroutine (CalculateDistance ());
}

// We use a coroutine so that we can force update canvas and wait for the frame.
IEnumerator CalculateDistance () {
    // First we will force the canvas to update with the following:
    Canvas.ForceUpdateCanvases ();
    yield return new WaitForEndOfFrame ();
    Canvas.ForceUpdateCanvases ();
    // Now we can calculate distance regularly (using whatever method you prefer). Example below:
    Vector2 posA = elementA.position;
    Vector2 posB = elementB.position;
    float myDistance= Vector2.Distance (posA, posB);
    Debug.Log("Distance: " + myDistance);
}

}

Hope this helps someone. :slight_smile:

It seems that when comparing the above result with the square of the desired distance worked. However, this was not the case before replacing the Player object with a FPS one.

So changing the following code I eventually got the desired results:

if (distance > (maxRunRange * maxRunRange)) {
...
}

instead of

if (distance > maxRunRange) {
...
}

which used to work before.