Debug.DrawLine (Help!)

Hello Unity,

I am trying to draw line between my character and the enemy, everything seems to be fine on my end but it doesn’t work. I have either no errors or warnings and my character is tagged “Player”.
I am sharing the code, please do let me know what’s wrong.

Regards,
M.Aqib

using UnityEngine;
using System.Collections;

public class EnemyAI : MonoBehaviour
{

    public Transform target;

    public GameObject playerFinder;
    private Transform myTransform;



    void Awake()
    {
        myTransform = transform;
    }

    void Start()
    {
        playerFinder = GameObject.FindGameObjectWithTag("Player");
        target = playerFinder.transform;
    }

    void Update()
    {

        Debug.DrawLine(target.position, myTransform.position, Color.yellow);
    
    }
}

2634719--185273--Player_Tag.png

Sounds odd! I suppose it should not do any difference since you’re calling drawLine from the Update function, but you could try adding the duration the line should be seen.

Debug.DrawLine( target.position, myTransform.position, Color.yellow, 1f );

But as far as I can see there’s nothing wrong with your code, you could also try to create an OnDrawGizmos member and use Gizmos.DrawLine instead?

public void OnDrawGizmos(){
if( target != null ){
Gizmos.DrawLine( target.position, myTransform.position, Color.yellow );
}
}
1 Like

Debug.Draw is not enable by default in the game window, you need to enable the draw gizmo option. Though it should be always visible in the editor window.

1 Like

if there is no error, then its finding the player and drawing the line, otherwise you would’ve gotten a Null reference exception on target.position.

Just like the Handles class, I honestly think it makes more sense to me that the Debug class should only load into a build if “Developmental build” is checked, by being in UnityEditor assembly to help enforce the idea that it shouldn’t run during a released build. Same with Gizmos class which normally shows up only in scene view (unless you have that “show gizmos” on, which again only works in editor). they are considered Editor utilities, not classes to be used in the released game.

If you want to see this line in the game during a build then don’t use the Debug or gizmos classes. Use a Line Renderer

1 Like
Debug.DrawLine( target.position, myTransform.position, Color.yellow, 1f );

The code worked properly, what is “1f” you have added in the code ?

Thanks for sharing clarified code, it helped me learn :smile:

All of you, thanks for helping!
Cheers :stuck_out_tongue:

http://docs.unity3d.com/ScriptReference/Debug.DrawLine.html

fourth parameter is “duration”, defaults to 0f.