Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

detect pickupable item via camera raycast

Discussion in 'Scripting' started by Line-Smith, Jul 17, 2022.

  1. Line-Smith

    Line-Smith

    Joined:
    Jul 5, 2022
    Posts:
    4
    i'm struggling with finding anything that works. I need to make a system that sends a raycast from the center of the camera view to detect a specific layer, "pickupable", and then note down the game object.

    here's my current code (which doesn't work)
    Code (CSharp):
    1.    
    2.     public Camera camera;
    3.     public GameObject itemPicked;
    4.  
    5.     public float pickupRange;
    6.     public LayerMask pickupable;
    7.    
    8.     // Start is called before the first frame update
    9.     void Start()
    10.     {
    11.         camera = GetComponent<Camera>();
    12.     }
    13.  
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    17.         Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    18.        
    19.         RaycastHit hit;
    20.         if (Physics.Raycast(ray, out hit, pickupRange) && hit.transform.gameObject.layer ==          LayerMask.NameToLayer("pickupable"))
    21.         {
    22.             Debug.DrawLine(ray.origin, Camera.main.transform.forward * 50000000, Color.red);
    23.  
    24.             print("I'm looking at an item" + hit.transform.name);
    25.  
    26.             itemPicked = hit.transform.gameObject;
    27.         }
    28.  
    29.         else
    30.         {
    31.             print("I'm looking at nothing!");
    32.  
    33.             itemPicked = null;
    34.         }
    35.     }
     
  2. Line-Smith

    Line-Smith

    Joined:
    Jul 5, 2022
    Posts:
    4
    nvm lol fixed it