- Home /
 
LayerMask for RayCast
I have no idea why this isn't working.... if anyone can help me, I really appreciate it!
my script attached to my camera:
 using UnityEngine;
 using System.Collections;
 
 public class placingObjectScript : MonoBehaviour 
 {
     public bool treeSelected = true;
     public GameObject[] tree;
 
     void Update ()
     {
         if(Input.GetMouseButtonDown(0))
         {
             Ray ray;
             RaycastHit hit;
             ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 
             if(Physics.Raycast(ray, out hit, 1 << 3))
             {
                 if(treeSelected && hit.collider.tag == "placableGround")
                 {
                     Instantiate(tree[Random.Range (0, tree.Length)], hit.point, Quaternion.identity);
                 }
             }
         }
     }
 }
 
 
               I have assigned everything to the default layer, and then the camera to Ingore Raycast. The camera has a collider, and without using layers, the trees will spawn on the camera's collider.
At the moment, when you click, nothing happens. It works when I get rid of the camera collider and the layer mask bit, but I really need a camera collider...
http://docs.unity3d.com/ScriptReference/Physics.Raycast.html
It seems there are no overloaded methods for Physics.Raycast(Ray, out hit, Layer$$anonymous$$ask) so I think your raycast have a lenght of 8 ^^
Answer by IsaiahKelly · May 16, 2015 at 01:20 AM
You're putting the layerMask value where maxDistance is supposed to go. It's also way easier to use a LayerMask popup to set the value in the inspector. And CompareTag is faster than comparing strings directly. See if this helps:
 using UnityEngine;
 using System.Collections;
 
 public class placingObjectScript : MonoBehaviour 
 {
     public LayerMask mask = -1;
     public bool treeSelected = true;
     public GameObject[] tree;
     
     void Update ()
     {
         if(Input.GetMouseButtonDown(0))
         {
             Ray ray;
             RaycastHit hit;
             ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             
             if(Physics.Raycast(ray, out hit, Mathf.Infinity, mask.value))
             {
                 if(treeSelected && hit.collider.CompareTag("placableGround"))
                 {
                     Instantiate(tree[Random.Range (0, tree.Length)], hit.point, Quaternion.identity);
                 }
             }
         }
     }
 }
 
              Your answer
 
             Follow this Question
Related Questions
Layermask (raycast) wont work... 4 Answers
Colliders attached to objects on separate layers are colliding? 1 Answer
How to create User layer that acts like the "Ignore Raycast" layer? 1 Answer
Detecting that I'm clicking a unit even though I'm not? 0 Answers
Why is Physics.Raycast returning colliders in a layer not included in the layermask? 2 Answers