Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How to get distance Unity5? /Javascript/

Discussion in 'Scripting' started by Rautmanis, Jul 16, 2015.

  1. Rautmanis

    Rautmanis

    Joined:
    Jul 16, 2015
    Posts:
    2
    Hi.
    I’m new to Unity5 and I’m having some issues..
    How do I get Unity5 to measure distance from FirstPersonCharacter to any other object that the character is looking at..?

    I've tried something like this ->

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

    But the distance always stays at 0.

    Please help!
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,386
    Where do you define the objects? Post your whole script, use code tags.
     
  3. Rautmanis

    Rautmanis

    Joined:
    Jul 16, 2015
    Posts:
    2
    I have something like this.


    #pragma strict

    var TheDammage : int = 50;
    var Distance : float;
    var MaxDistance : float = 1.5;
    var TheSystem : Transform;


    function Update ()
    {
    if (Input.GetButtonDown("Fire1"))
    {


    }

    }

    function AttackDammage ()
    {
    var hit : RaycastHit;
    if (Physics.Raycast(TheSystem.transform.position, TheSystem.transform.TransformDirection(Vector3.forward), hit))
    {
    Distance = hit.distance;
    if (Distance < MaxDistance)
    {
    hit.transform.SendMessage("ApplyDammage", TheDammage, SendMessageOptions.DontRequireReceiver);
    }
    }
    }
     
  4. SomeGuy22

    SomeGuy22

    Joined:
    Jun 3, 2011
    Posts:
    722
    Good job not using Code Tags~

    You should use Debug.Log to make sure distance is happening correctly. Also where are you calling your AttackDammage() function?? (Man that spelling is horrendous lol) Debug.Log(Distance) and also Debug.DrawLine(transform.position, hit.point) to make sure your Raycast is hitting. You might want to check a LOT more things such as Collision Layers, the fact that SendMessage should probably go to .gameObject instead of .transform. And finally (nitpicking here) instead of using Transform direction, just use TheSystem.forward. It's already a transform so no need for that extra work.