Search Unity

Why Isn't My Line Drawing?

Discussion in 'Scripting' started by AdamCNorton, Sep 22, 2014.

  1. AdamCNorton

    AdamCNorton

    Joined:
    Apr 16, 2013
    Posts:
    57
    So to me it seems like this code should do a Raycast, and alert me when it hits the player. It should also draw a DebugLine so I can see it. But neither of those things are happening. Can anyone see what I'm missing?

    Code (CSharp):
    1. public void Alert()
    2.     {
    3.         if(!alerted)
    4.         {
    5.             RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector3.right, searchDist * -1, collisionMask);
    6.             Debug.DrawLine(transform.position, new Vector3(transform.position.x + searchDist, transform.position.y, transform.position.z));
    7.             if(hit.collider != null)
    8.             {
    9.                 if(hit.collider.tag == "Player" && playerLoco.hidden == false)
    10.                 {
    11.                     Debug.Log("Ray has hit: " + hit.collider.name);
    12.                 }
    13.             }
    14.         }
    15.     }
     
  2. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    239
    If the code is ran every frame then the line should be visible, but otherwise you wont see it (e.g. if it's called from Update, you should see a line).

    Also just an improvement suggestion, to aid code readability and to ensure your line is being drawn correctly:
    Code (CSharp):
    1. public void Alert()
    2. {
    3.     if(!alerted)
    4.     {
    5.         Ray ray = new Ray(transform.position, Vector3.right);
    6.         RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, searchDist * -1, collisionMask);
    7.         Debug.DrawLine(ray.origin, ray.origin + (ray.direction * (searchDist * -1)));
    8.         if(hit.collider != null)
    9.         {
    10.             if(hit.collider.tag == "Player" && playerLoco.hidden == false)
    11.             {
    12.                 Debug.Log("Ray has hit: " + hit.collider.name);
    13.             }
    14.         }
    15.     }
    16. }
    17.  
    Ray is 3D but can store the details of your origin and direction for your raycast, makes it easier to ensure your line is being drawn correctly. Hope this helps! :)
     
  3. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    You'd want to use Debug.DrawRay if you're doing to debug rays. You can use DrawLine but it's simpler just to use DrawRay.

    --Eric