Helpp
Code:
There’s no Mover object attached to the GameObject on which this code is running. (GetComponent only looks at the current object)
Null means nothing. You see a null reference exception when a reference variable is supposed to reference something but it’s actually referencing nothing.
For example, you have GetComponent in your code. If your GameObject has a Mover component then this code will return a reference to your Mover, but if your GameObject doesn’t have a Mover, than GetComponent() will return null, and null.StartMoveAction won’t work.
same with hit. If Physics.Raycast(GetMouseRay, out hit); actually hits something, then that method will set hit to a new RaycastHit object. If the raycast doesn’t hit anything, then it will set hit to null and then null.point won’t work.
First Use Debug.Log to find out which of your objects is null. Then try to find out why the object is null and make sure that you set it to a value somewhere.
This is not quite accurate. RaycastHit is a struct and a variable of that type can never be null, just full of invalid data.
Adding onto the guidance already posted above, these are always the same, and the answer to fix it is always the same… ALWAYS. It is the single most common error ever.
Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!
Some notes on how to fix a NullReferenceException error in Unity3D
The basic steps outlined above are:
Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.
You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:
This is the kind of mindset and thinking process you need to bring to this problem:
https://discussions.unity.com/t/814091/4
Step by step, break it down, find the problem.
Here is a clean analogy of the actual underlying problem of a null reference exception:
Oops. Good to know! ![]()
Another heads-up: both RaycastHit and RaycastHit2D are structs, but the way they are used is fundamentally different.
For Raycast (3D) the “hit” comes back as a boolean:
RaycastHit hit;
if (Physics.Raycast(...))
{
// did hit
}
For Raycast (2D) it comes back as a the non-nullness of the collider:
RaycastHit2D hit = Physics2D.Raycast(...);
if (hit.collider != null)
{
// did hit
}
Kinda non-orthogonal, unfortunately. But not massively weirdly different.
thank you bros:)