Search Unity

Question How to access a MonoBehaviour class from a static class

Discussion in 'Scripting' started by Bonobo_UK, Feb 25, 2024.

  1. Bonobo_UK

    Bonobo_UK

    Joined:
    Feb 3, 2024
    Posts:
    3
    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

    Code (CSharp):
    1. public static class GameManager
    2. {
    3.     public static int BlocksLeft { get; set; }
    4.     public static int LivesLeft { get; set; }
    5.     public static int CurrentLevel { get; set; }
    6.     public static int BlocksDestroyedThisRound { get; set; }
    7.     public static int BlocksDestroyedAllGame { get; set; }
    8.     public static SpawnManager spawnManager { get; set; }
    9. }
    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
     
  2. flashframe

    flashframe

    Joined:
    Feb 10, 2015
    Posts:
    797
    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:

    Code (CSharp):
    1. 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.
     
    SisusCo and Bonobo_UK like this.