Physics2d hit.collider.name is not work

I’m a beginner with Unity and I am trying to use Physics2D. I’m trying to get the ray to tell me if it’s hitting something, but it doesn’t seem to cooperate with me. Every time I trying to get the collider name, it just says ‘Object reference not set to an instance of an object’. I’ve trying to instantiate the object by code, it doesn’t work; I use a prefab of the object, it doesn’t work. Can someone help please?

If the raycast has hit nothing, there then is no collider, thus no game object to pull the name from.

Two issues I seen in your code. First, you’re comparing hit == null which will never work as RayCastHit2D is a struct, meaning a value type, and never null (I’m surprised we can ever compare structs against null).

You want to check the hit.collider or hit.gameObject for null to actually test if the raycast has hit anything.

Secondly… you never actually use the raycast hit. So it will always be empty. You’ll want to be using the overloads of Physics2D.Raycast that out a hit for you to use.

@spiney199
I only checked for null because a post for a similar problem on ‘Stack Overflow’ had said to try that, but since I know that it doesn’t do anything, I took out.

Also, where do I put the
out hit in the code?
I tried putting it in the raycast: Physics2D.Raycast (mousePos, Vector2.up, out hit), but that caused an error in the code.

Right I forget the 2d raycast is weird.

Consult the docs on the best overload to use: Unity - Scripting API: Physics2D.Raycast

Probably just use the overload that returns a RaycastHit2D.

Update: I found out that I did have to check for null, but in a very specific. It’s really stupid, but it works.