Legacy Documentation: Version 2017.2 (Go to current version)
LanguageEnglish
  • C#
  • JS

Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

NavMeshAgent.Raycast

Suggest a change

Success!

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Close

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Close

Cancel

public method Raycast(targetPosition: Vector3, out hit: AI.NavMeshHit): bool;
public bool Raycast(Vector3 targetPosition, out AI.NavMeshHit hit);

Parameters

targetPosition The desired end position of movement.
hit Properties of the obstacle detected by the ray (if any).

Returns

bool True if there is an obstacle between the agent and the target position, otherwise false.

Description

Trace a straight path towards a target postion in the NavMesh without moving the agent.

This function follows the path of a "ray" between the agent's position and the specified target position. If an obstruction is encountered along the line then a true value is returned and the position and other details of the obstructing object are stored in the hit parameter. This can be used to check if there is a clear shot or line of sight between a character and a target object. This function is preferable to the similar Physics.Raycast because the line tracing is performed in a simpler way using the navmesh and has a lower processing overhead.

var target: Transform;

private var agent: UnityEngine.AI.NavMeshAgent;

function Start () { agent = GetComponent.<UnityEngine.AI.NavMeshAgent>(); }

function Update() { var hit: UnityEngine.AI.NavMeshHit;

// Note the negative test condition! if (!agent.Raycast(target.position, hit)) { // Target is "visible" from our position. } }
using UnityEngine;
using UnityEngine.AI;

public class ExampleClass : MonoBehaviour { public Transform target; private NavMeshAgent agent;

void Start() { agent = GetComponent<NavMeshAgent>(); }

void Update() { NavMeshHit hit; if (!agent.Raycast(target.position, out hit)) { // Target is "visible" from our position. } } }

Did you find this page useful? Please give it a rating: