How To Create Raycasting to a Object?

Hi i am new to unity .i have a problem with ray casting i wrote a code like given below

using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
public RaycastHit hit;
public float Distances=15.0f;
void Start () {
}
void Update ()
{
Ray ray=new Ray(transform.position,Vector3.forward);
if (Physics.Raycast(ray,out hit,Distances))
{
Debug.DrawRay(transform.position,transform.TransformDirection(Vector3.forward)*Distances,Color.red);
}
else
{
Debug.DrawRay(transform.position,transform.TransformDirection(Vector3.forward)*Distances,Color.blue);
}
}
}

Here problem is when my object is going towards targets sometimes it showing red color ray(hiting) and again going towards next target its showing blue color ray(not hiting).help me…

Your Raycast() is using the world forward, but your Debug.DrawRay() is using the local forward of the object. Assuming your Debug.DrayRay() is your intent, change your Raycast() to:

Ray ray=new Ray(transform.position,transform.forward);

The use of ‘transform.forward’ instead of Vector3.forward makes the ray relative to the direction of the object casting the ray.