I’m trying to clamp a planet’s x axis between two values but I keep getting errors. Planet2’s value is not null
Here’s my code:
if (planet2.eulerAngles.x < -90)
planet2.eulerAngles = new Vector3(-90, 0, 0);
if (planet2.eulerAngles.x > 90)
planet2.eulerAngles = new Vector3(90, 0, 0);
It gives me the object reference error during runtime, and whenever the planet reaches the bound, it jumps to another location. Yes, I tried Mathf.Clamp, but it did exactly the same thing.
Identify what is null ← any other action taken before this step is WASTED TIME
Identify why it is null
Fix that.
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:
drag it in using the inspector
code inside this script initializes it
some OTHER external code initializes it
? something else?
This is the kind of mindset and thinking process you need to bring to this problem:
Step by step, break it down, find the problem.
Here is an analogy of a null reference:
I give you an empty cookie jar
I tell you to take a cookie from the jar
Your job is to identify which jar is empty, find out why it is empty, and fix that.
I know what a null reference error is, I just can’t find what object is null, the only variable on the line listed in the error is planet2, which I know is not null as it rotates correctly when I tell it to.
The error can’t be wrong, so do some debugging and confirm what’s going on.
You’re probably just making an assumption and perhaps there’s just two scripts in the scene, one assigned and one null. You can find this out yourself by debugging.
then add a null check a line before the error and when null issue a Debug.LogError("planet2 is null,this);
The “this” is in the context parameter (e.g. the monobehaviour instance the logerror was called in) which means when you click on the log unity’s console it will highligh the exact gameobject with the monobehaviour throwing the exception.
there you can check if its the script you are thinking of or if some duplicate script is getting created and thats what throwing the error
In general, DO NOT use Find-like or GetComponent/AddComponent-like methods unless there truly is no other way, eg, dynamic runtime discovery of arbitrary objects. These mechanisms are for extremely-advanced use ONLY.
If something is built into your scene or prefab, make a script and drag the reference(s) in. That will let you experience the highest rate of The Unity Way™ success of accessing things in your game.
“Stop playing ‘Where’s GameWaldo’ and drag it in already!”