How to find nearby objects?

Hi, I am trying to control the four corners of the mouse with raycasting. At the distance I specify, if there is a tag, write “found! :)” on the console.

if (Physics.Raycast (hit.transform.position, Vector3.left, out hit, 1.0f)
    || Physics.Raycast (hit.transform.position, Vector3.right, out hit, 1.0f)
    || Physics.Raycast (hit.transform.position, Vector3.forward, out hit, 1.0f)
    || Physics.Raycast (hit.transform.position, Vector3.back, out hit, 1.0f)) {
    if (hit.collider.transform.tag == "redbox") {
    print ("found! :)");
    }
}

But it does not work and it always gives the same error.

NullReferenceException: Object reference not set to an instance of an object

I want to check around the mouse.I am trying to do this using raycast.I do not know if there is any other way of doing this, It did not work in the alternative ways I thought.Below is the mouse that appears as a result of right clicking.

92137-draw.png

Is it possible to find out which tag is in the ending points of the gray colored lines?

you’re using hit.transform.position as the raycast start where hit is your out parameter for the result and it’s transformis of course null because it has not been used and filled at that time. Use the mouse position instead.

You are trying to raycast out from the position of ‘hit’, which does not exist yet. You want to raycast out from the transform itself. Physics.Raycast (in the way you are using it) does not take in the hit parameter, only a variable to store the information of the hit if there is one, hence ‘out hit’. Try this:

 if (Physics.Raycast (transform.position, Vector3.left, out hit, 1.0f)
     || Physics.Raycast (transform.position, Vector3.right, out hit, 1.0f)
     || Physics.Raycast (transform.position, Vector3.forward, out hit, 1.0f)
     || Physics.Raycast (transform.position, Vector3.back, out hit, 1.0f)) {
     if (hit.collider.transform.tag == "redbox") {
     print ("found! :)");
     }
 }

Also of note, you should use CompareTag rather than .tag == “redbox”.