Search Unity

How to raycast for a specific component?

Discussion in 'Scripting' started by markashburner, Jul 16, 2019.

  1. markashburner

    markashburner

    Joined:
    Aug 14, 2015
    Posts:
    212
    can someone help me with my code?

    I am trying to get the raycast to return a hit value of a number of GameObjects with the PlanetSelection component.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class MouseManager : MonoBehaviour
    6. {
    7.     public GameObject selectedObject;
    8.  
    9.  
    10.     void Update()
    11.     {
    12.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    13.         RaycastHit hitInfo;
    14.    
    15.             if (Physics.Raycast(ray, out hitInfo))
    16.             {
    17.                 /////This is where I look for the gameObjects with the PlanetSelection components.
    18.                 GameObject hitObject = hitInfo.transform.GetComponent<PlanetSelection>().gameObject;
    19.                
    20.                     SelectObject(hitObject);
    21.                
    22.             }
    23.             else
    24.             {
    25.                 ClearSelection();
    26.             }
    27.  
    28.     }
    29.  
    30.     void SelectObject(GameObject obj)
    31.     {
    32.         if (selectedObject != null)
    33.         {
    34.             if (obj == selectedObject)
    35.                 return;
    36.             ClearSelection();
    37.         }
    38.         selectedObject = obj;
    39.     }
    40.  
    41.     void ClearSelection()
    42.     {
    43.         selectedObject = null;
    44.     }
    45. }
    it's telling me object reference is not set to an instance of an object....it's because I don't have any objects with the component <PlanetSelection> in the scene just yet as those are instantiated later. This is the error I get: NullReferenceException: Object reference not set to an instance of an object MouseManager.Update () (at Assets/_Scripts/MouseManager.cs:25) It's because of my Update method....How do I make it only check when there are <PlanetSelection> components in the scene?
     
  2. grizzly

    grizzly

    Joined:
    Dec 5, 2012
    Posts:
    357
    I'd suggest setting up collision layers and using the raycast's layerMask first and foremost, but if you can't use layers, then you'll need to check whether GetComponent succeeds;
    Code (CSharp):
    1. PlanetSelection planet = hitInfo.transform.GetComponent<PlanetSelection>();
    2.  
    3. if (planet != null)
    4. {
    5.     SelectObject(planet.gameObject);
    6. }
     
    markashburner likes this.
  3. markashburner

    markashburner

    Joined:
    Aug 14, 2015
    Posts:
    212
    Thanks man!