Search Unity

Trouble with layers

Discussion in 'Editor & General Support' started by Tempus_G, Mar 25, 2021.

  1. Tempus_G

    Tempus_G

    Joined:
    May 12, 2015
    Posts:
    53
    I am trying to have a select and move object setup.
    Two functions with two raycasts to target the given layer.
    Layer "IsClickable" for objects that I wish to select from, and "IsGround" layer to say what objects to move around on.
    Code (CSharp):
    1.     [SerializeField] private LayerMask layerMask1;
    2.     [SerializeField] private LayerMask layerMask2;
    Code (CSharp):
    1. if (Input.GetMouseButtonDown(0))
    2.         {
    3.             if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit, layerMask1))
    4.             {
    5.                 if(hit.transform != null)
    6.                 {
    7.                     if (!hit.transform.parent)
    8.                     {
    9.                         currentObject = hit.transform.gameObject;
    10.                         Debug.Log(" " + hit.transform.gameObject);
    11.                     }
    12.                     else
    13.                     {
    14.                         currentObject = hit.transform.parent.gameObject;
    15.                         Debug.Log(" " + hit.transform.parent);
    16.                     }
    17.                 }
    18.              }
    19.         }

    Code (CSharp):
    1. if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hitInfo, layerMask2))
    2.             {
    3.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    4.             Debug.DrawRay(ray.origin, ray.direction * 100, Color.yellow);
    5.             currentObject.transform.position = hitInfo.point;
    6.              currentObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
    7.         }
    What I get though is the outcome that you would, if you had one ray ,and the selected object flying at the camera!

    I thought that layers were supposed to help. But no matter what layer they are on, as long as they have a layer, I get the same outcome.
     
    Last edited: Mar 31, 2021
  2. Tempus_G

    Tempus_G

    Joined:
    May 12, 2015
    Posts:
    53
    Ok. After searching, I found some info about ray length. I always thought that a ray was infinite unless stipulated.
    But seems that I needed to Implicitly set length. So I inserted "Mathf.Infinity" to the code on both.

    Code (CSharp):
    1. (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out RaycastHit hit, Mathf.Infinity, layerMask1)
    This seems to have fixed it.