Search Unity

Bug Can't get script from raycast

Discussion in 'Scripting' started by Rematchia, Oct 2, 2021.

  1. Rematchia

    Rematchia

    Joined:
    Jan 20, 2017
    Posts:
    2
    Solved
    The script keeps spitting an error out
    the error says: "Object reference not set to an instance of an object"
    Code (CSharp):
    1. private int layermask = 1 << 8;
    2.     private RaycastHit hit;
    3.  
    4.     // Update is called once per frame
    5.     void Update()
    6.     {
    7.         if (Input.GetMouseButtonDown(1))
    8.         {
    9.             if (Physics.Raycast(transform.position, transform.forward*3f, layermask))
    10.             {
    11.                 Debug.Log("gaming");
    12.                -- errors here \/
    13.                 if (hit.collider.gameObject.GetComponentInParent<DoorOpenScript>()) {
    14.                     DoorOpenScript theOther = hit.collider.gameObject.GetComponentInParent<DoorOpenScript>();
    15.                     theOther.DoorUsed();
    16.  
    17.                 }
    18.             }
    19.  
    20.         }
    21.  
    22.     }
     
    Last edited: Oct 2, 2021
  2. BABIA_GameStudio

    BABIA_GameStudio

    Joined:
    Mar 31, 2020
    Posts:
    497
    You have defined a variable called
    hit
    , but never actually assign anything to it - so of course it is going to be null. Perhaps you should be using one of the versions of the Raycast method where you can get info of what you actually hit and then use that variable.
     
  3. Rematchia

    Rematchia

    Joined:
    Jan 20, 2017
    Posts:
    2
    oomph! that was fairly obvious thanks