Calculate the distance between an object and my player

Hey

I’m trying to load a screen after my player gets to the shop.
Does anyone know how to calculate the distance between an object you click on and the player.


  1. I think i would need to find a way
    to record the gameObject click on,
    but i’m having no luck finding how
    to do that.
  2. then i would probably record the location of the player and do the math from there.

right now in my code you can click on a destination and the character will go there. I just need to be able to calculate the distance and load the screen if it gets close enough.

For your point 1: Use a Raycast from your camera. The RayCastHit will return information about the collider that was hit, including the transform:

void Update()
 {
     if( Input.GetMouseButtonDown(0) )
     {
         Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
         RaycastHit hit;
         
         if( Physics.Raycast( ray, out hit, 100 ) )
         {
             Debug.Log( hit.transform.gameObject.name );
         }
     }
 }

For Point 2: Use this to calculate distance between two objects:

var distance = Vector3.Distance(object1.transform.position, object2.transform.position);