Is there anyway to check whether a raycast hits a certain layer? I’m trying to do some basic pathfinding with an “objects” layer and a “ground” layer. I want it so that if the raycast hit’s the object layer it wont generate a new path. I’m just not sure how to detect whether or not it hits it.
This is an example how you do a raycast with the mouse on all the layers. If the raycast hits the Ground it prints out “Ground”, else it prints out “Other Objects”. You did not mention how the raycast would be thrown. PS. You can edit Mathf.Infinity to whatever distance you want the raycast to go, and you can add more of those if statements like: else if (hit.transform.gameObject.layer==LayerStairways) and so on.
JS:
private var LayerGround;
private var CastRays : boolean = true;
function Start () {
LayerGround = LayerMask.NameToLayer("Ground");
}
function Update () {
if (CastRays) {
var ray = Camera.mainCamera.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
// Raycast
if (Physics.Raycast(ray, hit, Mathf.Infinity)) {
if (hit.transform.gameObject.layer == LayerGround) {
Debug.Log("Ground");
// Make a path
} else {
Debug.Log("Other Objects");
// Do whatever you want
}
}
}
}
C#:
using UnityEngine;
using System.Collections;
public class Pathing : MonoBehaviour {
private int LayerGround;
private bool CastRays = true;
void Start () {
LayerGround = LayerMask.NameToLayer("Ground");
}
void Update () {
if (CastRays) {
Ray ray = Camera.mainCamera.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
// Raycast
if (Physics.Raycast(ray, out hit, Mathf.Infinity)) {
if (hit.transform.gameObject.layer == LayerGround) {
Debug.Log("Ground");
// Make a path
} else {
Debug.Log("Other Objects");
// Do whatever you want
}
}
}
}
}
RaycastHit hit ;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition) ; //or whatever you’re doing for your ray
float distance = 123.123f ; //however far your ray shoots
int layerMask = 1<< 7 ; // “7” here needing to be replaced by whatever layer it is you’re wanting to use
layerMask = ~layerMask ; //invert the mask so it targets all layers EXCEPT for this one
if(Physics.Raycast(ray, out hit, distance, layerMask)){
//do stuff
}