How toshow distance between objects in beatiful way?

Hello, I have a task - to show the distance between the objects along the axis x. And, I need to show the distance between the objects as a line, and on top of the line - in fact the value itself. Is there a ready-made solution for this? If not, in what direction to dig? I can define the distance in numbers, but here’s how to draw a line and display the value on this line? Moreover, a single object can be moved, and the line should be changed.

Is this for the editor or for in-game?

You need to supply more information. Posting a couple of pictures of what you want might be helpful. - Is this 2D or 3D? - As @jbarba_ballytech asks, is this in the editor or in-game? - If you move one of the objects, do you mean move it on the line or move it out of order to create a path? - Do you restrict objects to be between other objects? There is no read-made solution for problem.

Ok, thanks for the questions, it is in the game, can move only one object, the second is in place and does not move, it is necessary to draw a line between them and show the distance.

2 Answers

2

You should do this with a line renderer. Look at the script reference, and just set your vertex count to 2 and have one vertex at the start object, one at the end object.

As for text hovering above, there are a whole bunch of ways to do this. The easiest might be a simple OnGUI call. You can get the position of the objects in screen space like so:

Do this for the two objects and then take the average - that’ll give you a point halfway along the line. Move up a little in the y-direction and create your text. You can do that with:

One thing to keep in mind: GUI space is flipped vertically from screen space. GUI assumes that +y is down (you paint from top to bottom), while in screen space +y is up. So you’ll need to do something like:

flippedPos = Screen.height - yPos;
  • You can draw a line at runtime using the LineRenderer class.
  • Finding the distance between object can be done using Vector3.Distance().
  • But before you can calculate the distance, you are going to have to get a reference to the objects in your script. One way is GameObject.Find().
  • To display the calculated distance you can use GUI.Label().

The more difficult part of your project is drag and drop. If it is a 3D game, then you have the added complexity of how to deal with a 3D environment with a 2D device (mouse/finger). Drag and Drop has been solved on this list 100’s of times. I recommend you start your project with figure out how to drag one game object around the screen.