Script that calculates distance between player and another object?

Hello guys,i m new and i have no idea how to write the code myself.Could anyone be kind and post a script that would calculate the distance between the player and an object X?I would like to be able to see the distance ingame,so in real time while the player is moving away or closer to the object.Thanks in advance if you help me out :wink:

^ This page generally answers this, but unity has a built in method to compare two points and get the distance between:

2 Likes

@MD_Reptile has it spot on. Just use Vector3.Distance

hi,thx for your reply.Google brought me to your 2nd link too,i dont understand anything of it though.As i said in my original post,i don’t understand the code,i have zero experience with it.
Can you post the complete script?If it is too much work,it’s ok i understand,you don’t have to do it

Well heres untested code that should work:

public Transform OneTransform;
public Transform AnotherTransform;
    void Update() {
        if (OneTransform) {
            float dist = Vector3.Distance(OneTransform.position, AnotherTransform.position);
            print("Distance to other: " + dist);
        }
    }

And with that you can either create a new script to test it, and replace the Update method with this one, and add those variables to the top, and assign in inspector.

1 Like

Hello and thx again for the help!So i tried your code but i get errors.

The errors i get are two,the one says ‘‘Unexpected token:Transform’’ and the other one says ‘’; expected.Insert a semicolon in the end’'.
In your code there is already semicolon in the end so no idea why does such an error show up.

Do i get the errors because i need to tweak some of the variables for my scene?I tried replacing ‘‘one’’ and ‘‘another’’ from your code(dont laugh if its stupid) with ‘‘player’’ and ‘‘x’’(this is the name of the object that i want to know how close to the player is) but this didn’t work either.
Also did i attach the script correctly?I attached it to the main camera,which is child of ‘‘Player’’,should i attach it somewhere else?

EDIT:Oh my,i just realized it’s C,i saved the code as js,sry i m so stupid.I get another error now though,it says ‘‘A namespace can only contain types and namespace declarations’’

Ok now make sure you start with a new script (create c# script in the editor) and then don’t erase it when your in monodevelop/whatever code editor, just replace the Update method to match my example, and at the top of the class where you declare variables (below the line with MonoBehavior) put the “public Transform WhateverNameYouWantForTheVariableNames;” parts (SomeTransform and AnotherTransform) and it should work.

If you can’t get that going I’ll get on my pc later and write a better example.

Good luck!

1 Like

I’d suggest you start by running through all of these, at least the beginner section.

1 Like

Thx for the suggestion but do i have to learn all this for just a script?I will look into them but i m sure i will give up quickly because there are so many things about programming languages that i dont understand.

hello,thx for not giving up yet :slight_smile:
So if i understand correctly i should write it like this?

using UnityEngine;
using System.Collections;

public class distance_calculator : MonoBehaviour {
    public Transform OneTransform;
    public Transform AnotherTransform;
    // Use this for initialization
    void Start () {
 
    }
 
    // Update is called once per frame
    void Update () {
            if (OneTransform) {
                float dist = Vector3.Distance(OneTransform.position, AnotherTransform.position);
                print("Distance to other: " + dist);
            }

}

I get another error now saying this:
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.AddComponentWindow.GetChildren (.Element[ ] tree, UnityEditor.Element parent) (at C:/BuildAgent/work/d3d49558e4d408f4/Editor/Mono/Inspector/AddComponentWindow.cs:887)
UnityEditor.AddComponentWindow.CreateComponentTree () (at C:/BuildAgent/work/d3d49558e4d408f4/Editor/Mono/Inspector/AddComponentWindow.cs:476)
UnityEditor.AddComponentWindow.OnGUI () (at C:/BuildAgent/work/d3d49558e4d408f4/Editor/Mono/Inspector/AddComponentWindow.cs:505)

Generally, when someone comes here with questions, it’s best to learn something about why the problem happened so it can be avoided in the future - don’t just let us solve your problem now, let us help you solve it forever.

If this is the only script you’ll ever need, then we can hand you the answer and send you on your way. If you ever plan on writing or modifying any other scripts, though, then do the tutorials. They are really beginner-level coding concepts, and even with no background in coding you should have little problem following along as long as (a) you start from the beginning (b) you don’t skip any and (c) If he says “For more information about X, check Y”, you go check Y if you don’t understand what’s going on.

If you’re really averse to learning any code, I’d suggest looking into Playmaker or something.

2 Likes

Of course i m willing to learn,otherwise i wouldnt be here in the first place.If you would explain to me my mistakes on the code that would be great,thx

The script you posted in your most recent comment should be correct. You just need to make sure that both references (OneTransform and AnotherTransform) are assigned by dragging objects into those slots in the inspector.

Edit: upon closer reading of the error, it appears to be coming from Unity’s interface, not your script. Try restarting the Editor, making sure you’re on the latest version, and that sort of thing. If the message keeps appearing, file a bug report with Unity. (Help → Bug Report)

1 Like

THANK YOU,it finally works,i would have never figured it out myself!Consider this thread solved :slight_smile:

Happy developing! If you need to get some practice with C#, I always recommend the stuff at 3DBuzz - they have a bunch of good video tutorials that explain things pretty well and should help you become more proficient.

2 Likes

+1 for 3DBuzz, they have some great free Unity tutorials, good for beginners and intermediate C# coders. I haven’t checked out their paid tutorials, but I imagine they are pretty decent too judging by the free ones.