How to access a MonoBehaviour class from a static class

Hi,

I have a GameManager static class I use for keeping track of scores, lives and what not.

I’m trying to reference other classes in this static class, for example the SpawnManager monobehaviour class.

I’m trying to do something like

public static class GameManager
{
    public static int BlocksLeft { get; set; }
    public static int LivesLeft { get; set; }
    public static int CurrentLevel { get; set; }
    public static int BlocksDestroyedThisRound { get; set; }
    public static int BlocksDestroyedAllGame { get; set; }
    public static SpawnManager spawnManager { get; set; }
}

But this throws an error as the GameManager obviously doesn’t know what a SpawnManager is.

My plan was to have the spawnManager instance set GameManager.spawnManager to be itself on startup. How can I import this class into the GameManager? Is this even possible if spawnManager is an instance?

Thanks in advance

Yes, you can assign the spawnManager the same way you’d assign any of the other variables.

So in the Awake or Start function of SpawnManager you can assign:

GameManager.spawnManager = this;

Of course this relies on only having a single SpawnManager in your scene. Another option is to search for the SpawnManager in the scene the first time you try to access it.

Ps. Nothing wrong with calling the variable SpawnManager with Pascal case to be consistent with your other variables.

2 Likes