Raycast Vision


I have made a script that allows a Enemy to find a player thats within a circle around it then chase the player until it enters its Range which is a float of 15. It works very smoothly but has one big problem. If the players standing behind a wall or tree then the enemy can attack through it.

I had an idea that the Enemy could use raycast for vision and if it can see the player clearly then it will attack. If the player is behind a wall then the Enemy would find the closest way around it and simply run around.

Anyways I am really bad at raycast and It would be really helpful if someone could just give me a script to get me started.

Well here’s a basic raycast you could modify:


function Update () {
    var fwd = transform.TransformDirection (Vector3.forward);
    if (Physics.Raycast (transform.position, fwd, 10)) {
        print ("There is something in front of the object!");


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Update() {
        Vector3 fwd = transform.TransformDirection(Vector3.forward);
        if (Physics.Raycast(transform.position, fwd, 10))
            print("There is something in front of the object!");

Then you could make the raycast check for the object by doing (Javascript)

if (Physics.Raycast (transform.position,hitinfo,fwd, 10)) {
        if (hitinfo.transform.tag == "Player")
          //do attack

Unity’s Documentation On Raycast, it has a few examples that you can use to get started.

You may also need to look at Raycast Layer Mask for more advance raycast behaviour.