Static classes and references are bad for Builds... Alternatives?

Hi there! Yeah… that sucks… I’ve just found out that most of the problems I’ve been experiencing lately with my builds are related to static classes and references.

Well, static classes most often than not.

Since I’ve never been taught about " good practices" when coding, before I do something my own way that I’ll eventually have to regret, I’d like to hear from you what would be the optimal solution.

Here’s my condition:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public static class References {

	//Static variable to reference the Obstacles layer
	static LayerMask _obstaclesMask;
	public static LayerMask ObstaclesMask{

			_obstaclesMask = 1 << 8; 

			return _obstaclesMask;

This Reference class is the one that keeps bringing up problems, it seems its values ( or the whole class itself) is null somehow when inside a build.

That class just holds properties that I reference throughout various other classes.

I need to swap that public static class with something else… maybe a script that inherits from MonoBehaviour that I can attach to a Singleton game object, so I know it’s always there and its values are accessible.

But, again, I’d like to hear from you what should be done in this case.

And also, if you could tell me once again why static classes are bad… why is this screwing up?

Thanks :smiley:


I have a static class that holds references to multiple things as well. I have never had any issues with it, even in actual builds, but there is a caveat.

The trick is to make sure it isn’t getting garbage collected… as long as you are accessing this static class frequently enough, it should never get garbage collected.

You are correct however in that the “proper” way to go about this is to use a singleton pattern on a monoBehavior. This will prevent you from having to worry about your static class getting garbage collected.

Hope that helps.