Accessing Static variable from another class gives null value!

Hi all,

I am stuck with this error for many hours … Will appreciate your inputs on this.

I am trying to use a variable as a global by declaring it static in class “Init”. Initially, I am returning the Gameobject using FindWithTag into a static Gameobject variable in class “Init” and using its SetActive property to set it to false. Later on, I am trying to access this variable from another class “csblock1” and trying to reset it to true using “Init.hidez[0].setActive(true)”. At this point, I am getting a console message “NullReferenceException: Object Reference not set to an instance of an object”

Even though I have initialized the static variable in class “Init”, how does it return null when I am trying to access from class “csblock1” ?

Thanks in advance,
Anhal[78301-csblock1.txt|78301]

As you say in your comments, your Start function might be called more than once. This is because your script is a MonoBehaviour and, as such, it can be attached to many GameObjects. However, they all share the static variable hidez.

In addition, keep in mind that FindWithTag will not find deactivated objects.

So, what is probably going here is this:

  1. First instance of Init correctly finds the desired GameObjects and deativates them.
  2. Second instance of Init does not find any object, so it overwrites the static variable with null objects.
  3. When csblock1 tries to access the static array, it finds only null values.

So, the solution: Make sure that there is only one instance of Init in the scene. Or even better, don’t make this script a MonoBehaviour at all, unless you really need it. Make it a singleton.